top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the concept of Singleton class in standalone app or in simple java program?

+2 votes
410 views
What is the concept of Singleton class in standalone app or in simple java program?
posted Jun 24, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Singleton class means only one instance of class can exist.

Creating Singleton class

creating INSTANCE variable

Make it private > So that INSTANCE variable cannot be accessed outside class.

Make it static > So that INSTANCE variable can be accessed in static methods of class.

Make it Singleton type> So that INSTANCE variable can be refer to Singleton object.

creating private constructor

Make it private > so that class can't be instantiated outside this class.

creating getInstance method

Method which will return instance (only instance) of Singleton class.

Method will perform double check and ensure no two threads form more than one instance.

Method is public so that it could be accessed outside class.

Method is static so that it could be accessed without creating instance of class.

Use synchronized block inside method-so that 2 threads don’t create more than 1 instance of class concurrently.

/* 
* Singleton class - with Double checked Locking


class SingletonDoublyLocked {

private static SingletonDoublyLocked INSTANCE;

/* 
* private constructor 
*/ 
private SingletonDoublyLocked() { 
}

public static SingletonDoublyLocked getInstance() { 
//First check - To avoid more than one instance creation of Singleton class. 
if (INSTANCE == null) { 
synchronized (SingletonDoublyLocked.class) { 
//Second check - To avoid more than one instance creation of 
//Singleton class. 
if (INSTANCE == null) { 
INSTANCE = new SingletonDoublyLocked(); 
} 
} 
} 
return INSTANCE; 
}      
}

Let’s discuss in detail about logic of Doubly Locked Singleton class

if (INSTANCE == null) {


synchronized (SingletonDoublyLocked.class) {

 if (INSTANCE == null) {

INSTANCE = new SingletonDoublyLocked();

}

}

Let's say there are two threads t1 and t2 .
Let’s say t1 enters synchronized block reaches line 3, now t2 can’t reach line3 until t1 don’t leave synchronized block. By the time t1 must be waiting at line 2 after (INSTANCE == null) returned true at line 1.
Before leaving synchronized block t1 must have instantiated INSTANCE at line 4. After t1 leaves synchronization block, t2 will enter synchronized block and (INSTANCE == null) at line4 will return false because t1 already instantiated INSTANCE.

FROM This Refer

answer Jun 24, 2015 by Karthick.c
...