简体   繁体   中英

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.

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.

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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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