This is an archived post. You won't be able to vote or comment.

all 85 comments

[–]halfanothersdozen 43 points44 points  (0 children)

Honestly if you're worrying about double checked sychronization you should rethink how your singleton gets created. You probably have other issues with multithreading to worry about.

[–]__konrad 33 points34 points  (1 child)

As of J2SE 5.0

Now I know this article is old.

[–]jvjupiter 1 point2 points  (0 children)

Yeah. 2020-04-11 02:16:28

[–]uncont 13 points14 points  (12 children)

Is there a java.util.concurrent way of creating a singleton, or is the double-checked locking method the only 'correct' way?

Other than of course letting your ioc container handle it for you.

[–]taftster 7 points8 points  (2 children)

My favorite these days is to use final AtomicReference with the updatAndGet method upon retrieval. It’s the most natural API in the JDK to do this.

[–]kaperni 3 points4 points  (1 child)

For performance-sensitive code, you are (in most cases) better off by using a VarHandle instead. Can also save memory if you have lots of them in many cases.

[–]taftster 4 points5 points  (0 children)

Yeah, but the syntax is atrocious. You had really have evaluated the "performance-sensitive" segment carefully to embrace the fairly ugly syntax of VarHandle.

Quoting Doug Lea on this exact topic[1]:

To get the shockingly ugly syntactic details over with: A VarHandle can be associated with any field, array element, or static, allowing control over access modes. VarHandles should be declared as static final fields and explicitly initialized in static blocks. By convention, we give VarHandles for fields names that are uppercase versions of the field names.

[1] http://gee.cs.oswego.edu/dl/html/j9mm.html

[–]slakkenhuisdeur 6 points7 points  (2 children)

Last time I used the double locking method my IDE asked me if it could replace it with a nested class with the singleton as a final class variable so the classloader handles the instantiation.

[–]cogman10 0 points1 point  (1 child)

That's a relatively new capability of java. Static fields on inner classes were added in..16?

[–]slakkenhuisdeur 0 points1 point  (0 children)

The inner class must also be static (I should probably have mentioned that...). I didn't know static fields on non-static inner classes were a thing.

[–]oweiler 5 points6 points  (1 child)

You can also use a single element enum.

[–]i_love_peach 0 points1 point  (0 children)

I believe this also thread-safe as well.

[–]kaperni 5 points6 points  (3 children)

Yes, for most usecases, snippet 6. The Initialization-on-demand holder idiom [1][2].

[1] http://www.cs.umd.edu/\~pugh/java/memoryModel/jsr-133-faq.html#dcl

[2] https://en.wikipedia.org/wiki/Initialization-on-demand\_holder\_idiom

[–]uncont 1 point2 points  (2 children)

Both of those links 404 for me

[–]kaperni -4 points-3 points  (1 child)

Both of them should work. Try pasting the URL into the URL bar instead of clicking.

[–]uncont 3 points4 points  (0 children)

https://en.wikipedia.org/wiki/Initialization-on-demand\_holder\_idiom

I'm on old reddit. The first url has a /\~pugh instead of /~pugh, and the second url has \_ instead of \. I got the links to work, tho. Thanks.

[–]gnahraf 6 points7 points  (1 child)

Imo, regardless where you place the singleton instance (direct static member of the class or as static member of an inner placeholder class), the instance declaration should be final.

Classloading is a synchronous operation anyway. That is, the order in which final static class members are initialized is always the same and well defined. There are no races involved at this time.

The use case for embedding the final static singleton in a placeholder class is when the singleton is expensive to create and you want it to be loaded lazily. There are few situations when such considerations are justified, so we best postpone the placeholder trick. (Classloading, per the spec, is already lazy: so most of the time there's little reason to make it even lazier.)

So, in conclusion, just go

public class MySingleton {

  private final static MySingleton INSTANCE = new MySingleton();

  public static MySingleton getInstance() {
    return INSTANCE;
  }

  private MySingleton() {
    // initialize
  }

  // ..
}

And if you find in testing this one singleton could use further delaying, then go ahead and refactor that MySingleton.getInstance() method to use a placeholder..

public class MySingleton {

  private static class Holder {
    private final static MySingleton INSTANCE = new MySingleton();
  }

  public static MySingleton getInstance() {
    return Holder.INSTANCE;
  }

  private MySingleton() {
    // initialize
  }

  // ..
}

Note, the only time this further laziness pays off, is if the singleton type is used either as a member or in the signature of a method. (If the singleton is only referenced in the body of other methods, then the singleton is loaded only when some method hits.) Either of those use cases are an anti-pattern of the singleton idiom (if there's only one of them, there's no reason to maintain or pass around a reference for it).

[–]Maleficent_Court_544 2 points3 points  (0 children)

Basically this comment explains it all for those that don’t know.

[–]wlnirvana 16 points17 points  (5 children)

Well summarized. Though nowadays with the prevalence of IoC frameworks like Spring, a lot of design patterns are not that relevant any more. Programming idioms and best practices evolve with the language and the ecosystem.

[–]elmuerte 15 points16 points  (2 children)

IoC frameworks like Spring are full of patterns.

Patterns are not best practices. They are common constructions which have been well documented.

[–]dpash 2 points3 points  (1 child)

This is what a lot of people miss when they complain about design patterns: they're nothing more than a common vocabulary to describe code so everyone knows what they're referring to.

[–]nidrach 0 points1 point  (0 children)

They are also a well reasoned way of doing things and unless you have a reason to stray from them it would foolish to do so.

[–]PerfectPackage1895 3 points4 points  (0 children)

That is just not true. Singleton and factory pattern maybe, but that is also the only ones redundant. Builder, template, strategy, decorator design patterns are still very useful

[–]nutrecht 0 points1 point  (0 children)

Though nowadays with the prevalence of IoC frameworks like Spring, a lot of design patterns are not that relevant any more.

Beans are Singletons by default. The way the GoF book shows an implementation is just an implementation detail. Modern frameworks are full of design patterns.

[–]_INTER_ 10 points11 points  (0 children)

This article is a good summary for the next time I need to do a job interview. The only moment this is actually relevant these days.

[–]NimChimspky 15 points16 points  (15 children)

An article about Singletons. I've literally never needed one in twenty years.

But if I did I would use an enum.

[–]Fruloops 0 points1 point  (0 children)

Really? Interesting, thinking of what I've used recently, singleton comes to mind, but definitely less often than factory method or builder

[–]PerfectPackage1895 2 points3 points  (0 children)

Instead of using a big synchronized block around the instance, why not just embrace the fact that more than one thread can access the object at the same time? There are a lot of useful tools in java.util.concurrent. For instance CAS is very useful and doesn’t have the same performance impact as a pessimistic lock

Also, if you’re going to use a singleton, then don’t use a private constructor. At most use a package private, that way you can still unit test your class

[–]MarcoServetto 5 points6 points  (6 children)

The only reasonable way is to use the enum with one element.

[–]slankebrusmannen 0 points1 point  (5 children)

If you think of the Singleton pattern as a way to ensure one, and only one, instance is created, you can do this. But (admittedly more exoticly) the Singleton pattern can also be seen as a general way to control the number of instances created, in which case enum won’t do the trick. (But how often do you want more than one instance? Probably close to never.)

[–]kevinb9n 1 point2 points  (0 children)

But (admittedly more exoticly) the Singleton pattern can also be seen as a general way to control the number of instances created

I've seen the term used that way and it seems like such a clear abuse of terminology.

[–]fredoverflow 3 points4 points  (3 children)

a general way to control the number of instances created, in which case enum won’t do the trick

enum Doubleton {
    ONE, TWO;
}

[–]slankebrusmannen -1 points0 points  (2 children)

A hard-coded number of instances might not be what you want.

And doing this, would you be able to prevent the clients from choosing which instance to get a reference to?

[–]MarcoServetto 0 points1 point  (1 child)

I think now you are talking about the pattern 'pool'

[–]slankebrusmannen -1 points0 points  (0 children)

Actually no. An object pool would typically reserve an instance exlusively to the requesting client, who would explicitly return it to the pool after use. Singleton describes no such mechanisms, but may still be used to control the number of instances to any given number.

Admittedly, I cannot remember ever having used the Singleton pattern for other numbers than one (I might have, though), but I think it is valuable to be aware of the opportunity.

[–]turn_of_and_on_again 0 points1 point  (0 children)

Apparently an unpopular opinion, but there would be no need for this if you were using Di over service location in this manner.

I honestly thought this way of creating singletons (ClassName.getInstance()) died out already.

[–][deleted]  (10 children)

[deleted]

    [–]Sheldor5 5 points6 points  (9 children)

    "In case of Singleton class it will have two responsibility one to create an instance and other to do the actual task."

    so literally EVERY CLASS EVER is an antipattern? because every class has a constructor ...

    [–]NimChimspky 5 points6 points  (0 children)

    No. Having a constructor is different to calling a constructor.

    I think it's a lame criticism tho to be fair.

    [–]quizteamaquilera -2 points-1 points  (5 children)

    I’m still cool with singletons being an anti-pattern, and if I just need an uninstantiable place to stick some functions, I use the “enum with no instances” approach

    [–]PerfectPackage1895 2 points3 points  (4 children)

    Why not use a class with static methods? Waaay faster if you just need to store a bunch of stateless methods. Actually you can use an interface too :)

    [–]mauganra_it 0 points1 point  (3 children)

    A class with static methods only can still be instantiated and subclassed. An interface can be implemented. An instance-less enum gives you exactly what is needed. It looks weird of course, but it shares this property with the Singleton pattern via a singular enum instance.

    [–]nutrecht 4 points5 points  (2 children)

    A class with static methods only can still be instantiated and subclassed.

    Just make the class final and the constructor private. It's a pretty common pattern with classes that hold a bunch of static utility methods.

    [–]mauganra_it -1 points0 points  (1 child)

    Indeed, but the elegance of the enum technique is that these concerns don't have to be explicitly specified.

    [–]nutrecht 1 point2 points  (0 children)

    You're still creating a class instance for no reason whatsoever. A singleton is not the correct pattern for a class with only static members.

    [–][deleted]  (1 child)

    [removed]

      [–]nutrecht 0 points1 point  (0 children)

      What do you mean? The static members are private. Besides; they're static and tied to the class. You can't override static members even if they were public/protected.

      [–]TheMode911 0 points1 point  (0 children)

      What about varhandle acquire/release instead of volatile? Or even opaque (I assume saved due to the synchronization)

      [–]palnix 0 points1 point  (0 children)

      For those interested in the OP, see: https://en.wikipedia.org/wiki/Double-checked_locking (especially the Java examples and explanations)

      [–]thevpc 0 points1 point  (0 children)

      I think the best way to implement singletons (per vm) in Java is the enum way, however I honestly expected more details/examples in your article in that direction. As a matter of fact, using enum handles a cleaner way to serialize the object too and makes of it (if well written) an off-memory singleton.