I was interested to learn about singleton in enum and performance.
When we have a multi-threaded environment, we must synchronize the moment when an instance is created.
We can just use a synchronized mod for a function called getInstance () that instantiates something like this:
public synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
This is a lazy implementation, this is good for me. But the synchronized method is slow. We can use double locking to make it faster.
How about the listing? When we implement singleton as enum, a singleton instance will be created as the first use. Next use, return the current instance.
How it works? When we want to get an existing instance, is there an implicit synchronized method that is slow? Or is a double lock implemented?
source
share