Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 11

How should i ideally write Singleton and thread safe class without using any synchronization

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?

Upvotes: 0

Views: 101

Answers (1)

Sonika
Sonika

Reputation: 11

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;
}

Upvotes: 1

Related Questions