简体   繁体   English

如何使线程安全的单例类(保存状态)

[英]How to make a thread safe singleton class (that holds state)

I know that singleton classes are inherently not thread-safe. 我知道单例类本质上不是线程安全的。 But is there any way to make it so? 但是有没有办法做到这一点? I have a singleton in a java web application, and I want one class to exist per user of this program. 我在Java Web应用程序中有一个单例,并且我希望该程序的每个用户都存在一个类。

This is an issue because the singleton holds state, otherwise it'd be fine. 这是一个问题,因为单例保持状态,否则就可以了。

I have a singleton in a java web application, and I want one class to exist per user of this program. 我在Java Web应用程序中有一个单例,并且我希望该程序的每个用户都存在一个类。

It makes no sense to make it a singleton. 使它成为单例是没有意义的。 Just make it a session attribute. 只需将其设置为会话属性即可。 The HttpSession is tied to the browser session and specific for every visitor. HttpSession绑定到浏览器会话,并且特定于每个访问者。 For example, the shopping cart: 例如,购物车:

Cart cart = (Cart) session.getAttribute("cart");

if (cart == null) {
    cart = new Cart();
    session.setAttribute("cart", cart);
}

// ...

It can just be a simple Javabean. 它可以只是一个简单的Javabean。

See also: 也可以看看:

Your question isn't really making a lot of sense to me in that you ask for "one class to exist per user of this program." 对于我来说,您的问题并不是很有意义,因为您要求“该程序的每个用户都存在一个类”。 I'm guessing you mean you would like one instance to exist per user, in which case you are not looking for a singleton, but an instance of a bean that is within session scope. 我猜您的意思是您希望每个用户存在一个实例,在这种情况下,您不是要查找单个实例,而是要在会话范围内查找bean实例。

A singleton object is an object with only one instance across the system. 单例对象是整个系统中只有一个实例的对象。

Singletons usually take on this pattern these days: 这些天,单例通常采用这种模式:

public class Singleton {
   // Private constructor prevents instantiation from other classes
   private Singleton() {
   }

   /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before.
    */
   private static class SingletonHolder { 
     public static final Singleton instance = new Singleton();
   }

   public static Singleton getInstance() {
     return SingletonHolder.instance;
   }
 }

See http://en.wikipedia.org/wiki/Singleton_pattern for singleton basics 有关单例基础知识,请参见http://en.wikipedia.org/wiki/Singleton_pattern

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM