What is an efficient way to implement a singleton pattern in Java? [closed]
Asked Answered
B

29

852

What is an efficient way to implement a singleton design pattern in Java?

Basic answered 16/9, 2008 at 9:24 Comment(3)
"What is an efficient way to implement a singleton pattern in Java?" please define efficient.Helve
medium.com/@kevalpatel2106/… . This is the complete article on how to achieve thread, reflection and serialization safety in the singleton pattern. This is the good source to understand the benefits and limitations of singleton class.Anent
As Joshua Bloch points out in Effective Java, enum singleton is the best way to go. Here I have categorized the various implementations as lazy/eager etc.Selfregulated
H
815

Use an enum:

public enum Foo {
    INSTANCE;
}

Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}

Edit: An online portion of "Effective Java" says:

"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

Hydrodynamic answered 16/9, 2008 at 11:31 Comment(28)
I think people should start looking at enums as just a class with a feature. if you can list the instances of your class at compile time, use an enum.Souvenir
Would you use an enum for a "utility" class?Reis
I personally don't often find the need to use the singleton pattern directly. I sometimes use spring's dependency injection with an application context that contains what it refers to as singletons. My utility classes tend to only contain static methods, and I don't need any instances of them.Hydrodynamic
@Tom - if it confers all the advantages provided by the compiler, yes, I would. An enum is simply just a class with additional constrains imposed by the compiler and run-time. They are not the same as the integer-based enums found in C or Pascal.Communal
Question: Where does logic usually placed in a constructor (i.e. run-once initialization for the singleton) go?Quadruplet
@Eric You can create a constructor, or use an initialization block.Hydrodynamic
Hi, Can anybody tell me how this type of singleton can be mocked and tested in test cases. I tried to swap fake singleton instance for this type but couldn't.Collimore
If you are looking for an example of this pattern in action, Google Guava uses this a lot for its private implementations: code.google.com/p/guava-libraries/source/browse/trunk/guava/src/…Yerga
@Tom, I would advocate using enum for Utility classes as well.Limewater
I guess it makes sense, but I still don't like it. How would you create a singleton that extends another class? If you use an enum, you can't.Oft
@eneveu the link you provided to Google Guava gives a 404 error.Barracuda
code.google.com/p/guava-libraries/source/browse/guava/src/com/…Hydrodynamic
@Subhra Thanks. Stephen Denne posted a link to the Functions class, and here is an updated link that goes directly to the enum singleton pattern example in the Guava code: code.google.com/p/guava-libraries/source/browse/guava/src/com/…Yerga
This is not the singleton design pattern, as it cannot implement interfaces. This is more akin to 'how can I only have 1 allocation of a struct (which can also have pointers to functions) in c'.Wayside
@zombies yes it can. selikoff.net/2011/06/15/java-enums-can-implement-interfacesBlackmore
You will never be able to use a super class, define a constructor, use an external factory function or to overrule it. It is a smart-ass solution to save 7 lines of code while sacrificing priceless flexibility.Soandso
@bvdb: If you want lots of flexibility, you've already screwed up by implementing a singleton in the first place. The ability to create an independent instance when you need it is rather priceless in itself.Trainband
well by far this is the best method of implementing a singleton, there might be another guy trying to edit your code and without knowing it as a singleton may create a new object of the class and use it just like any other normal class. this approach allows us not to create an object hence this is the best method.Lavaliere
While an enum technically accomplishes a singleton pattern most effectively, is it not also the most rigid? What if I decide my singleton should no longer be a singleton anymore? If I used an enum, I've got a lot of unpleasant refactoring to do. If I used a static getter, that is much more flexible and I could easily make it a ThreadLocal, etcDagmar
Is there a way to implement this also when I need to pass some parameters to the constructor? Let's say values from the config or dependency injection?Putrescine
@StephenDenne Enum only supporting in JDK5 onwards..Editheditha
I have to disagree with JB here, because it is he himself who disagrees with himself. E.g. he says "don't use interface to declare constants", and gives the reason that "constant use is not an interface, it produces semantic mismatch and noise, and the syntactic sugar gained (no need to use static final etc.) is not worth it". He uses a similar argument couple of times in EJ2... By analogy, one would say "don't use enum to declare singleton class; singleton is not an enum - it produces semantic mismatch and noise, and the syntactic sugar gained is not worth it"Parasiticide
I've seen this advice floating around the internet for years. It's an interesting use of enum but semantically, I just can't do it. An enum with a single value happens to be a singleton but that's really not what an enumeration is, conceptually. And I'm not sure I've ever had much need for an "ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks." :)Julee
From what I've found on this, this is not very memory efficient though.Madelle
An enum for a singleton is also correct from the perspective of set theory. A class is an infinite mutable runtime-defined set of objects. An enum is a finite, immutable, compile time-defined set of objects. A singleton is a finite, immutable, compile time-defined set of objects. Therefore, use an enum for Singletons. Also, use an enum for Utility classes. That's a more formal explanation for what @AmirArad said.Levitus
@Julee what you said is, conceptually, correct in other languages, but not in Java. In Java, that is exactlu what an enumariton is, conceptually. It is an enumeration of objects (not constants, constants is for other languages), and a Singleton is an enumeration of exactly one object.Levitus
@ChristianHujer Java enum values seem pretty constant to me. :) I think what you mean to say is that the values (objects) don't have to be immutable. static final List<Foo> FOOS = … is also a constant reference to an object that's not necessarily immutable. My point was just that the term "enum" generally implies both, even to well-seasoned Java developers. Since Java doesn't enforce enum immutability (just like it doesn't force FOOS above to be immutable,) you could use enum as a way to create a singleton of a heavyweight, mutable class. But it just feels like a misuse of the concept.Julee
@spaaarky21That is not at all what I meant to say. I wasn't talking about the objects, but the type. The set described by an enum is immutable. You cannot create a new instance of an enum at runtime. But you can of a class, just call new ClassName(), unless the class prevents it somehow, but per default it can.Levitus
I
241

Depending on the usage, there are several "correct" answers.

Since Java 5, the best way to do it is to use an enum:

public enum Foo {
   INSTANCE;
}

Pre Java 5, the most simple case is:

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");
    }
}

Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

public final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

Impact answered 16/9, 2008 at 15:44 Comment(15)
The check for reflection is useless. If other code is using reflection on privates, it's Game Over. There's no reason to even try to function correctly under such misuse. And if you try, it will be an incomplete "protection" anyways, just a lot of wasted code.Peccary
> "First, you want the class to be final". Could someone elaborate on this please?Vascular
The deserialisation protection is completely broken (I think this is mentioned in Effective Java 2nd Ed).Reis
-1 this is absolutely not the most simple case, it's contrived and needlessly complex. Look at Jonathan's answer for the actually most simple solution that is sufficient in 99.9% of all cases.Stewardson
No, it is not. As the language changes and time passes, progressive insight learned me that for java5 and later, the best way to do it is to use the enum solution, as suggested by spdenneImpact
Wow, this is way more complicated than I thought. At least enum method provides you with more of an "easy feeling" about stuff like serialization. What about threading?Suppository
This is useful when your singleton needs to inherit from a superclass. You cannot use the enum singleton pattern in this case, since enums cannot have a superclass (they can implement interfaces, though). For example, Google Guava uses a static final field when the enum singleton pattern is not an option: code.google.com/p/guava-libraries/source/browse/trunk/guava/src/…Yerga
I agree that Jonatahn's way is sufficient. Etienne, please point out the problem you discovered since java5in Jonathan's solutionDescendible
I love your lazy-init solution using FooLoader. Can this pattern also be used to ensure that a certain block of code is run only once, in a lazy manner? See my answer to that discussion here. Would love to get your feedback on this.Continuo
Yes. The classloader makes sure it is only executed once and only when the code is accessed.Impact
Can you please use some meaningful class instead of Foo?Gully
You don't need to define final a Singleton class, since it's effectively final by having all its constructors private.Polynesian
Although that is technically correct, I've found it useful for several reasons: - It documents the intend - It prevents IDE's from suggesting the type name after an extends keyword.Impact
@eric Do you have a suggestion? Elvis?Impact
This FooLoader class is entirely obsolete. All the other variants have the same laziness. Further, there is no need to override clone() (and ironically, the other variants do not bother to override it, so why does that one variant?)Spillar
U
152

Disclaimer: I have just summarized all of the awesome answers and wrote it in my own words.


While implementing Singleton we have two options:

  1. Lazy loading
  2. Early loading

Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.

The most simple way of implementing a singleton is:

public class Foo {

    // It will be our sole hero
    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            // SHOUT
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }
}

Everything is good except it's an early loaded singleton. Lets try lazy loaded singleton

class Foo {

    // Our now_null_but_going_to_be sole hero
    private static Foo INSTANCE = null;

    private Foo() {
        if (INSTANCE != null) {
            // SHOUT
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        // Creating only  when required.
        if (INSTANCE == null) {
            INSTANCE = new Foo();
        }
        return INSTANCE;
    }
}

So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero. So let’s protect it from evil multi threading:

class Foo {

    private static Foo INSTANCE = null;

    // TODO Add private shouting constructor

    public static Foo getInstance() {
        // No more tension of threads
        synchronized (Foo.class) {
            if (INSTANCE == null) {
                INSTANCE = new Foo();
            }
        }
        return INSTANCE;
    }
}

But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:

class Foo {

    // Pay attention to volatile
    private static volatile Foo INSTANCE = null;

    // TODO Add private shouting constructor

    public static Foo getInstance() {
        if (INSTANCE == null) { // Check 1
            synchronized (Foo.class) {
                if (INSTANCE == null) { // Check 2
                    INSTANCE = new Foo();
                }
            }
        }
        return INSTANCE;
    }
}

This is called the "double-checked locking idiom". It's easy to forget the volatile statement and difficult to understand why it is necessary. For details: The "Double-Checked Locking is Broken" Declaration

Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:

class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static volatile Foo INSTANCE = null;

    // The rest of the things are same as above

    // No more fear of serialization
    @SuppressWarnings("unused")
    private Object readResolve() {
        return INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.

Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    // Wrapped in a inner static class so that loaded only when required
    private static class FooLoader {

        // And no more fear of threads
        private static final Foo INSTANCE = new Foo();
    }

    // TODO add private shouting construcor

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    // Damn you serialization
    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

Yes, this is our very same hero :)

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.

And we have come so far. Here is the best way to achieve everything we did is best possible way:

public enum Foo {
    INSTANCE;
}

Which internally will be treated like

public class Foo {

    // It will be our sole hero
    private static final Foo INSTANCE = new Foo();
}

That's it! No more fear of serialization, threads and ugly code. Also ENUMS singleton are lazily initialized.

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

-Joshua Bloch in "Effective Java"

Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)

Updated it on my blog.

Unperforated answered 16/5, 2013 at 6:24 Comment(8)
Just a clarification: singletons implemented using enum are initialized lazily. Details here: stackoverflow.com/questions/16771373/…Homicidal
great answer. one last thing, override clone method to throw exception.Cerebration
@xyz nice explanations, I really enjoyed and learned very easily and I hope never forgot thisRoss
In the 5th piece of code, return type of readResolve() should be Object.Forfend
There's no 'Early loading' at all since JVM loads classes lazily.Brittneybrittni
There is a serialization problem with using enums as a singleton: Any member field values are not serialized and therefore not restored. See Java Object Serialization Specification, version 6.0. Another problem: No versioning — all enum types have a fixed serialVersionUID of 0L. Third problem: No customization: Any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization.Class
@BasilBourque that’s no problem at all. Deserializing a different state than what the current runtime’s singleton already has, contradicts the logic of a singleton. A singleton implies having exactly one state. That’s why the non-enum types have a readResolve() method supposed to drop the deserialized state and use the current runtime’s singleton instance instead. So it’s obviously much cleaner not to have serialized data in the first place. Further, the readResolve() attempt can break under certain circumstances, then, you have two instances of the “singleton” class.Spillar
All classes are lazily initialized. The double-checked-locking approach wastes resources trying to solve a problem that doesn’t exist at all.Spillar
A
125

The solution posted by Stu Thompson is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.

It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of Java Concurrency in Practice. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.

This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.

class Bar {
    private static class BarHolder {
        public static Bar bar = new Bar();
    }

    public static Bar getBar() {
        return BarHolder.bar;
    }
}
Astrodynamics answered 16/9, 2008 at 12:24 Comment(8)
Fair enough! I'm just comfortable with volatile and it's use. Oh, and three cheers for JCiP.Archespore
Oh, this is apparently the approach advocated by William Pugh, of FindBugz fame.Archespore
@Stu The first edition of Effective Java (copyright 2001) details this pattern under item 48.Tasha
@Bno: What about making constructor private?Unperforated
If Bar requires a complex or lazy initialization, this approach won't work. It's problematic because the instance is created in the class loading phase.Sarnen
@Sarnen Not quite. The instance is created in the class loading phase for BarHolder, which is delayed until the first time it's needed. Bar's constructor can be as complicated as you want, but it won't get called until the first getBar(). (And if getBar is called "too early" then you'll face the same problem no matter how singleons are implemented.) You can see the lazy class loading of the code above here: pastebin.com/iq2eayiRBreathed
@TiStrga nothing is ever executed “in the class loading phase”. Class loading and class initialization are two entirely different things. In fact, the static Bar bar field could be moved to the class Bar and nothing would change. It still would be lazily initialized (the first call to getBar() will trigger the initialization). The irony is that even the nested class solution relies on the fact that the initialization is deferred until the bar field is accessed the first time.Spillar
@Spillar all true, I was sloppier in my vocabulary seven years ago :-) I'll blame it on the impetuousness of youth (please don't ask how gray my beard already was)Breathed
A
95

Thread safe in Java 5+:

class Foo {
    private static volatile Bar bar = null;
    public static Bar getBar() {
        if (bar == null) {
            synchronized(Foo.class) {
                if (bar == null)
                    bar = new Bar();
            }
        }
        return bar;
    }
}

Pay attention to the volatile modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization does not take care of that--it only serializes access to that block of code.

@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.

Archespore answered 16/9, 2008 at 9:51 Comment(12)
Where can I learn more about the volatile modifier?Essayist
See comments of stackoverflow.com/questions/70689/…Tasha
I think it is important to mention about reflection attacks. True that most developers don't need to worry about, but it seems that examples like these (over Enum-based singletons) should include either code that protects against multiple-instantiation attacks or simply put a disclaimer indicating such possibilities.Communal
Volatile keyword is not needed here - as synchronization gives both mutual exclusion plus memory visibility.Lethargy
@Hemant: Synchronization is only skin deep when it comes to visibility. The synchronization is on the class object and not provide visibility with changes to static class members. It is the same as a more generic synchronization on an instance where changes to the instance variables unless explicitly and correctly dealt with via volatile, java.util.concurrency types, or whatever.Archespore
Is there a simple way of protecting the developer from directly using bar?Sarnen
Why bother with all this in Java 5+ ? My understanding is that the enum approach provides both thread safety and lazy initialization. It is also much simpler... Furthermore, if you want to avoid an enum, I'd still prevent the nested static class approach...Camelback
@Alexandros: As others have noted, this approach provides lazy initialization, if needed. Personally, I don't need lazy init much (and most people don't) but this is a valid, thread-safe singleton pattern if you do.Archespore
@Hemant: Only if all the threads synchronize on the synchronization point. It's not in this case. The changes to the internal fields are (unless the object Bar is immutable and all fields are final) visible to threads that synchronizes on Foo.class. Other threads might see only some of the changes, especially a thread could see the change to the reference but not the internal fields. On the other hand, if Bar is immutbale, and all its fields are final, then the guarantees provided by the jvm memory model upon assigning to a final variable guarantees that the changes will be visible.Involucrum
"Bno" changed user name. What answer is referred to?Nosh
@PeterMortensen Benno Richters (the answer above)Archespore
When you write private static final Bar bar = new Bar();, the initialization will be lazy too.Spillar
G
93

Forget lazy initialization; it's too problematic. This is the simplest solution:

public class A {    

    private static final A INSTANCE = new A();

    private A() {}

    public static A getInstance() {
        return INSTANCE;
    }
}
Greenness answered 16/9, 2008 at 9:49 Comment(14)
singleton instance variable can be made final also. e.g., private static final A singleton = new A();Disney
That effectively is lazy initialisation, since the static singleton won't be instantiated until the class is loaded and the class won't be loaded until it's needed (which will be right about the time that you first reference the getInstance() method).Hacker
If class A does get loaded way before you want the static to be instantiated, you can wrap the static in a static inner class to decouple the class initialisation.Reis
I agree with @Dan Dayer, this is example it is lazy initialization. If there were other methods on the class, then it might be...depends on which static method gets called first. (Imagine a public static void doSomething() in class A being called first--A is instanced, but not used.)Archespore
why would you have another static method in this class and not want to use its getInstance(). One class One Responsibility out the door?Rashad
AFAIK, Singleton instance variables should be declared as final as it ensures that the variable is properly initialized before other threads can access it.Bankston
i agree this answer is the simplest, and Anirudhan, there is no need to declare the instance final. No other thread will get access to the class while the static members are initialized. this is guaranteed by the compiler, in other words, all static initialization is done in a synchronized manner - only one thread.Descendible
This in fact may be a simple solution but how to pass any argument to the constructor of such implemented singleton?Prime
You can't pass arguments from the getInstance() method. I can't think of a useful case for that anyway. Would there be several types of singletons depending on the argument? If so, it's not a singleton any more.Greenness
This approach have one limitation: The constructor cannot throw a exception.Michaelis
FindBugs complains SI_INSTANCE_BEFORE_FINALS_ASSIGNEDFumatorium
so this is faster that using the synchronisation and volatile?Dredge
@rahulsharma of course, it is.Spillar
@Michaelis private static final A INSTANCE = new A(); is syntactic sugar for private static final A INSTANCE; static { INSTANCE = new A(); }. If you use the verbose form, you can add try {} catch {} blocks.Spillar
G
48

Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.

There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.

Gametocyte answered 16/9, 2008 at 9:33 Comment(1)
you can inject mock values with the traditional method too but i guess its not the standard / srping way so its extra work with only gain being legacy code ...Rashad
F
21

I'm mystified by some of the answers that suggest dependency injection (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.

So my answer to the OP would be (in all but the most trivial sample code) to:

  1. Use a DI framework like Spring Framework, then
  2. Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.

This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).

Footstep answered 16/9, 2008 at 12:6 Comment(4)
Perhaps because people disagree with you. I haven't downvoted you, but i do disagree: i think DI can be used to solve the same problems singletons are. This is based on understanding "singleton" to mean "an object with a single instance which is accessed directly by a global name", rather than just "an object with a single instance", which is perhaps slightly tricksy.Harriet
To expand on that slightly, consider a TicketNumberer which needs to have a single global instance, and where you want to write a class TicketIssuer which contains a line of code int ticketNumber = ticketNumberer.nextTicketNumber();. In traditional singleton thinking, the previous line of code would have to be something like TicketNumberer ticketNumberer = TicketNumberer.INSTANCE;. In DI thinking, the class would have a constructor like public TicketIssuer(TicketNumberer ticketNumberer) { this.ticketNumberer = ticketNumberer; }.Harriet
And it becomes somebody else's problem to call that constructor. A DI framework would do it with a global map of some sort; a handbuilt DI architecture would do it because the app's main method (or one of its minions) would create the dependency and then call the constructor. Essentially, the use of a global variable (or a global method) is just a simple form of the dreaded service locator pattern, and can be replaced with dependency injection, just like any other use of that pattern.Harriet
@TomAnderson I'm really confused as to why people 'dread' the service locator pattern. I think in most cases it's overkill or not needed at best, however, there are seemingly useful cases. With smaller number of params DI is definitely preferred, but imagine 20+. Saying the code isn't structured isn't a valid argument, because sometimes groupings of parameters just doesn't make sense. Also, from a unit testing perspective, I don't care about testing the service, just the business logic of it, and if it's coded right, then this would be easy. I only seen this need in very large scale projects.Avery
C
20

Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.

Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like inversion of control (IoC) or dependency injection (DI) for a nice middle ground.

If you really need one then Wikipedia has a good example of a proper implementation of a singleton.

Crocodile answered 16/9, 2008 at 9:48 Comment(1)
Agreed. It is more of a foundational class that kick-starts the rest of your application and if it were duplicated you will end up with a complete chaos (i.e single access to a resource or enforcing security). Passing global data all over your application is a big coupling red flag. Use it when you acknowledge you really need it.Elga
R
16

Following are three different approaches

  1. Enum

     /**
     * Singleton pattern example using Java Enum
     */
     public enum EasySingleton {
         INSTANCE;
     }
    
  2. Double checked locking / lazy loading

     /**
     * Singleton pattern example with Double checked Locking
     */
     public class DoubleCheckedLockingSingleton {
          private static volatile DoubleCheckedLockingSingleton INSTANCE;
    
          private DoubleCheckedLockingSingleton() {}
    
          public static DoubleCheckedLockingSingleton getInstance() {
              if(INSTANCE == null) {
                 synchronized(DoubleCheckedLockingSingleton.class) {
                     // Double checking Singleton instance
                     if(INSTANCE == null) {
                         INSTANCE = new DoubleCheckedLockingSingleton();
                     }
                 }
              }
              return INSTANCE;
          }
     }
    
  3. Static factory method

     /**
     * Singleton pattern example with static factory method
     */
    
     public class Singleton {
         // Initialized during class loading
         private static final Singleton INSTANCE = new Singleton();
    
         // To prevent creating another instance of 'Singleton'
         private Singleton() {}
    
         public static Singleton getSingleton() {
             return INSTANCE;
         }
     }
    
Roman answered 17/2, 2013 at 3:46 Comment(0)
E
16

There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.


The first attempt might look something like this:

public class MySingleton {

     private static MySingleton INSTANCE;

     public static MySingleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MySingleton();
        }
        return INSTANCE;
    }
    ...
}

Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().

But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.


private static MySingleton INSTANCE;

public static synchronized MySingleton getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new MySingleton();
    }
    return INSTANCE;
}

Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.


private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronize(MySingleton.class) {
            INSTANCE = new MySingleton();
        }
    }
    return INSTANCE;
}

Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null.

They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.


private static MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }
    return INSTANCE;
}

Here we issue another check from inside the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.

This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations.

Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.


private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    if (INSTANCE == null) {
        synchronized(MySingleton.class) {
            if (INSTANCE == null) {
                INSTANCE = createInstance();
            }
        }
    }
    return INSTANCE;
}

We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.

But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.


private static volatile MySingleton INSTANCE;

public static MySingleton getInstance() {
    MySingleton result = INSTANCE;
    if (result == null) {
        synchronized(MySingleton.class) {
            result = INSTANCE;
            if (result == null) {
                INSTANCE = result = createInstance();
            }
        }
    }
    return result;
}

Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.

I wrote an article about this recently. Deconstructing The Singleton. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.

Ecotype answered 12/7, 2017 at 16:6 Comment(5)
Could you please explain why BearerToken instance in your article isn't static? And what is it result.hasExpired()?Granadilla
And what about class MySingleton – maybe it should be final?Granadilla
@Granadilla The BearerToken instance is not static because it is part of the BearerTokenFactory - which is configured with a specific authoriztion server. There could be many BearerTokenFactory objects - each one having it’s own “cached” BearerToken that it hands out until it has expired. The hasExpired() method on the BeraerToken is called in the factory’s get() method to ensure it does not hand out an expired token. If expired, a new token will be requested fro authorization server. The paragraph following the code block explains this in greater detail.Ecotype
It is very well written, but why use the literal INSTANCE (all caps)? Isn't it against Java conventions for naming (even if it may be some kind of placeholder name)? Couldn't a better name be found?Nosh
@PeterMortensen you know, for the life of me I can not remember why I used all caps. lol. Maybe because it is used like a static final after it is set. IDK. ¯\_(ツ)_/¯Ecotype
Q
13

I use the Spring Framework to manage my singletons.

It doesn't enforce the "singleton-ness" of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.

Qulllon answered 22/9, 2008 at 20:44 Comment(0)
H
11

Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).

Honig answered 16/9, 2008 at 9:35 Comment(0)
A
11

If you do not need lazy loading then simply try:

public class Singleton {
    private final static Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() { return Singleton.INSTANCE; }

    protected Object clone() {
        throw new CloneNotSupportedException();
    }
}

If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:

public class Singleton {
    private static Singleton instance = null;

    private Singleton() {}

    public static Singleton getInstance() {
        if(null == instance) {
            synchronized(Singleton.class) {
                if(null == instance) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    protected Object clone() {
        throw new CloneNotSupportedException();
    }
}

As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.

Anurag answered 16/9, 2008 at 9:50 Comment(5)
The first version is best. Assuming the class does nothing other than provide a singleton, then it will typically be instantiated at about the same point as the one in the second version due to lazy class loading.Hacker
Double-checking is pointless for a static. And why have you made the protected clone method public?Reis
-1 your version of double checked locking is broken.Oakley
Also you need to make your singleton variable volatilePrefrontal
The first version is lazy and thread-safe.Brittneybrittni
I
11

Version 1:

public class MySingleton {
    private static MySingleton instance = null;
    private MySingleton() {}
    public static synchronized MySingleton getInstance() {
        if(instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }
}

Lazy loading, thread safe with blocking, low performance because of synchronized.

Version 2:

public class MySingleton {
    private MySingleton() {}
    private static class MySingletonHolder {
        public final static MySingleton instance = new MySingleton();
    }
    public static MySingleton getInstance() {
        return MySingletonHolder.instance;
    }
}

Lazy loading, thread safe with non-blocking, high performance.

Indifferent answered 1/4, 2015 at 11:14 Comment(0)
F
9

I would say an enum singleton.

Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity's sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.

The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.

/**
* Singleton pattern example using a Java Enum
*/
public enum Singleton {
    INSTANCE;
    public void execute (String arg) {
        // Perform operation here
    }
}

You can access it by Singleton.INSTANCE, and it is much easier than calling the getInstance() method on Singleton.

1.12 Serialization of Enum Constants

Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.

The process by which enum constants are serialized cannot be customized: any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.

Quoted from Oracle documentation

Another problem with conventional Singletons are that once you implement the Serializable interface, they no longer remain singleton because the readObject() method always return a new instance, like a constructor in Java. This can be avoided by using readResolve() and discarding the newly created instance by replacing with a singleton like below:

 // readResolve to prevent another instance of Singleton
 private Object readResolve(){
     return INSTANCE;
 }

This can become even more complex if your singleton class maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.


Good Read

  1. Singleton Pattern
  2. Enums, Singletons and Deserialization
  3. Double-checked locking and the Singleton pattern
Fantastic answered 17/1, 2013 at 5:31 Comment(0)
A
9

There are four ways to create a singleton in Java.

  1. Eager initialization singleton

     public class Test {
         private static final Test test = new Test();
    
         private Test() {
         }
    
         public static Test getTest() {
             return test;
         }
     }
    
  2. Lazy initialization singleton (thread safe)

     public class Test {
          private static volatile Test test;
    
          private Test() {
          }
    
          public static Test getTest() {
             if(test == null) {
                 synchronized(Test.class) {
                     if(test == null) {
                         test = new Test();
                     }
                 }
             }
             return test;
         }
     }
    
  3. Bill Pugh singleton with holder pattern (preferably the best one)

     public class Test {
    
         private Test() {
         }
    
         private static class TestHolder {
             private static final Test test = new Test();
         }
    
         public static Test getInstance() {
             return TestHolder.test;
         }
     }
    
  4. Enum singleton

     public enum MySingleton {
         INSTANCE;
    
         private MySingleton() {
             System.out.println("Here");
         }
     }
    
Arris answered 23/8, 2016 at 10:25 Comment(5)
(1) is not eager, it is lazy due to JVM class loading mechanism.Brittneybrittni
@Brittneybrittni when did I say eager loading, I said eager initialization.If u think both are same then what is eager loading.May be you should write a book and correct the mistakes committed by previous authors like Joshua Bloch.Arris
Effective Java is a great book, but definitely requires editing.Brittneybrittni
@Brittneybrittni what is eager loading, can u explain by exampleArris
Doing something 'eagerly' means 'as soon as possible'. For example, Hibernate supports loading relations eagerly, if required explicitly.Brittneybrittni
G
4

This is how to implement a simple singleton:

public class Singleton {
    // It must be static and final to prevent later modification
    private static final Singleton INSTANCE = new Singleton();
    /** The constructor must be private to prevent external instantiation */
    private Singleton(){}
    /** The public static method allowing to get the instance */
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

This is how to properly lazy create your singleton:

public class Singleton {
    // The constructor must be private to prevent external instantiation
    private Singleton(){}
    /** The public static method allowing to get the instance */
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
    /**
     * The static inner class responsible for creating your instance only on demand,
     * because the static fields of a class are only initialized when the class
     * is explicitly called and a class initialization is synchronized such that only
     * one thread can perform it, this rule is also applicable to inner static class
     * So here INSTANCE will be created only when SingletonHolder.INSTANCE
     * will be called
     */
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}
Gaivn answered 18/5, 2016 at 16:19 Comment(2)
Both are lazy, assuming the only thing you need from singleton is its instance.Brittneybrittni
@Brittneybrittni the first case will instantiate the singleton when the JVM initializes the class, the second case will only instantiate the singleton when calling getInstance(). But indeed if you don't have any other static methods in your class Singleton and you only call getInstance() there is no real difference.Gaivn
K
3

You need the double-checking idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the initialization on demand holder idiom.

In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.

public static final INSTANCE == ....
private Object readResolve() {
  return INSTANCE; // Original singleton instance.
} 
Kuth answered 2/8, 2011 at 20:41 Comment(0)
J
3

Various ways to make a singleton object:

  1. As per Joshua Bloch - Enum would be the best.

  2. You can use double check locking also.

  3. Even an inner static class can be used.

Jori answered 29/8, 2015 at 12:42 Comment(1)
Re Joshua Bloch: What are you referring to? A particular book or blog post? Please respond by editing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).Nosh
N
3

Enum singleton

The simplest way to implement a singleton that is thread-safe is using an Enum:

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}
Nashua answered 2/10, 2015 at 11:30 Comment(2)
How is this different from previous answers?Nosh
you should ask the other people this. As you can see this was answered in 2015, this was the most complete answer at the time :)Nashua
T
2

For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).

Throughput answered 22/5, 2013 at 18:51 Comment(0)
G
2

Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:

public class SingletonImpl {

    private static SingletonImpl instance;

    public static SingletonImpl getInstance() {
        if (instance == null) {
            instance = new SingletonImpl();
        }
        return instance;
    }

    public static void setInstance(SingletonImpl impl) {
        instance = impl;
    }

    public void a() {
        System.out.println("Default Method");
    }
}

The added setInstance method allows setting a mockup implementation of the singleton class during testing:

public class SingletonMock extends SingletonImpl {

    @Override
    public void a() {
        System.out.println("Mock Method");
    }

}

This also works with early initialization approaches:

public class SingletonImpl {

    private static final SingletonImpl instance = new SingletonImpl();

    private static SingletonImpl alt;

    public static void setInstance(SingletonImpl inst) {
        alt = inst;
    }

    public static SingletonImpl getInstance() {
        if (alt != null) {
            return alt;
        }
        return instance;
    }

    public void a() {
        System.out.println("Default Method");
    }
}

public class SingletonMock extends SingletonImpl {

    @Override
    public void a() {
        System.out.println("Mock Method");
    }

}

This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.

Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.

Gloom answered 14/8, 2016 at 12:8 Comment(0)
I
1

Simplest singleton class:

public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}
Interline answered 24/10, 2013 at 9:39 Comment(2)
this is the same as Jonathan's answer belowDescendible
Duplicate of this sibling answer by Jonathan posted five years earlier. See that answer for interesting comments.Class
W
0

I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.

public enum Singleton {
    INSTANCE;
}

And you are done!

Walburga answered 6/1, 2015 at 7:22 Comment(1)
This is already mentioned in other answers years ago.Paramaribo
G
0

Have a look at this post.

Examples of GoF Design Patterns in Java's core libraries

From the best answer's "Singleton" section,

Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)

  • java.lang.Runtime#getRuntime()
  • java.awt.Desktop#getDesktop()
  • java.lang.System#getSecurityManager()

You can also learn the example of Singleton from Java native classes themselves.

Granivorous answered 21/8, 2015 at 0:43 Comment(0)
H
0

The best singleton pattern I've ever seen uses the Supplier interface.

  • It's generic and reusable
  • It supports lazy initialization
  • It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.

See below:

public class Singleton<T> implements Supplier<T> {

    private boolean initialized;
    private Supplier<T> singletonSupplier;

    public Singleton(T singletonValue) {
        this.singletonSupplier = () -> singletonValue;
    }

    public Singleton(Supplier<T> supplier) {
        this.singletonSupplier = () -> {
            // The initial supplier is temporary; it will be replaced after initialization
            synchronized (supplier) {
                if (!initialized) {
                    T singletonValue = supplier.get();
                    // Now that the singleton value has been initialized,
                    // replace the blocking supplier with a non-blocking supplier
                    singletonSupplier = () -> singletonValue;
                    initialized = true;
                }
                return singletonSupplier.get();
            }
        };
    }

    @Override
    public T get() {
        return singletonSupplier.get();
    }
}
Herminahermine answered 10/9, 2018 at 21:5 Comment(0)
F
-3

Sometimes a simple "static Foo foo = new Foo();" is not enough. Just think of some basic data insertion you want to do.

On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is

public class Singleton {

    private static Singleton instance = null;

    static {
          instance = new Singleton();
          // do some of your instantiation stuff here
    }

    private Singleton() {
          if(instance!=null) {
                  throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
          }
    }

    public static getSingleton() {
          return instance;
    }

}

Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the static { } - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.

Fixing answered 16/9, 2008 at 17:38 Comment(1)
Not true. static variables are initialized along with static blocks when the class is loaded. No need to split the declaration.Keldah
T
-5
public class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
        if (INSTANCE != null)
            throw new IllegalStateException(“Already instantiated...”);
        }


    public synchronized static Singleton getInstance() {
        return INSTANCE;
    }

}

As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.

Tessera answered 8/11, 2013 at 0:36 Comment(1)
I don't think this will compile.Nosh

© 2022 - 2024 — McMap. All rights reserved.