Saved Bookmarks
| 1. |
Can you write a code for representing thread-safe singleton patterns in Java? |
|
Answer» A thread-safe singleton class is created which helps in object initialization in the presence of multiple threads. It can be done using multiple ways:
SINGLETON_INSTANCE; public void display(){ System.out.println("Thread-safe singleton Display"); } } // The Singleton class methods can be invoked as below ThreadSafeSingleton.SINGLETON_INSTANCE.show();
private static final ThreadSafeSingleton INSTANCE = new ThreadSafeSingleton(); private ThreadSafeSingleton(){ } public static ThreadSafeSingleton getInstance(){ return INSTANCE; } public void display(){ System.out.println("Thread-safe Singleon"); } } ThreadSafeSingleton.getInstance().display(); But the disadvantage of this way is that the initialization cannot be done lazily and the getInstance() method is called even before any client can call.
{ // Creating private instance to make it accessible only by getInstance() method private static ThreadSafeSingleton instance; private ThreadSafeSingleton() { // Making constructor private so that objects cant be initialized outside the class } //synchronized getInstance method synchronized public static ThreadSafeSingleton getInstance(){ if (this.instance == null) { // if instance is null, initialize this.instance = new ThreadSafeSingleton(); } return this.instance; } }
// Creating private instance to make it accessible only by getInstance() method private static ThreadSafeSingleton instance; private ThreadSafeSingleton(){ // Making constructor private so that objects cant be initialized outside the class } public static ThreadSafeSingleton getInstance(){ if (instance == null){ //synchronized block of code synchronized (ThreadSafeSingleton.class){ if(instance==null) { // initialize only if instance is null instance = new ThreadSafeSingleton(); } } } return instance; } } |
|