I have a question regarding a thread-safe Singleton pattern I found on Wikipedia.
public final 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;
}
}
If the synchronized block wasn't synchronized, would it be possible for 2 threads to create 2 objects simultaneously?
I need to explain the usage of "synchronized" for an assignment.
Thanks and best regards
If it wasn't synchronized, you could indeed have 2 threads create 2 objects.
While using synchronized, only 1 thread can enter the synchronized blocked at a time.
Edit:
It is worth noting that the null check inside of the synchronized block is actually very important - otherwise it would be possible to create 2 objects as well. – Amongalen (in comments)
Another way to achieve a Singleton pattern is the following. Only use this pattern if creating the object isn't a big problem to do as soon as the application starts:
public final class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}