0

I tried writing a Singleton class using eager loading, see my solution below. I have made the constructor private to prevent access and the member field private, too, so it can't be accessed outside class scope.

public class Test  {

    private static Test t = new Test();

    private Test() {

    }

    public static Test getInstance() {
        return t;
    }

}

So, is this piece thread safe, considering all the scenarios?

  • Possible duplicate of [Are Java static initializers thread safe?](https://stackoverflow.com/questions/878577/are-java-static-initializers-thread-safe) – Sebastian Jun 05 '18 at 11:55
  • The answer is the linked duplicate. You should make the static field final, though. Then you're done. – Sebastian Jun 05 '18 at 11:56
  • 1
    Use an enum for Singletons. It is that simple. https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java – Ben Jun 05 '18 at 12:05
  • Define _all the scenarios_ as you will still end up with two instances after serialization + deserialization. To fix, check [this answer](https://stackoverflow.com/questions/3930181/how-to-deal-with-singleton-along-with-serialization) – Nico Van Belle Jun 05 '18 at 12:12
  • @Sebastian thanks, Nico Van Belle, Yes correct i need to write readResolve method to prevent so, i was trying to understand other than using Enums, how we can design singleton well without using any synchronized keywords. – Himanshu Upadhyay Jun 06 '18 at 05:57

1 Answers1

1

use enum singleton pattern:

public enum xxton {
  INSTANCE;
}

Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.

I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum. More generally, you can provide a readResolve() method like so:

protected Object readResolve() {
  return myInstance;
}
Sonika
  • 11
  • 2
  • 2
    We have many similar answers, already mentioned in question comments section. – ajay tomar Jun 05 '18 at 12:21
  • 2
    This answer is a mix with copy/pasted answers from [here](https://stackoverflow.com/questions/3930181/how-to-deal-with-singleton-along-with-serialization) and [here](https://stackoverflow.com/questions/26285520/implementing-singleton-with-an-enum-in-java). Flagging it for admins – Nico Van Belle Jun 05 '18 at 12:22