0

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.

Steve
  • 4,457
  • 12
  • 48
  • 89

3 Answers3

4

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

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.

digitaljoel
  • 26,265
  • 15
  • 89
  • 115
1

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

Hyangelo
  • 4,784
  • 4
  • 26
  • 33
  • Except that the trendy thing now is to instantiate singletons in the context of an enum. In this way you avoid the potential snafus that can occur if the class is serializable. In Joshua Bloch's words, your "mono-Elvistic" universe can remain mono-Elvistic. – scottb Jun 19 '13 at 20:34
  • It is equivalent to this and more concise although something just feels weird about it. – Hyangelo Jun 28 '13 at 00:34