The algorithm for getting a singleton object of a class by using double checking for null instances as follows
But The question is why the instance is null checked twice in line no 7 and line no 10.It seems it is sufficient to check the instance as null once after synchronization block.The code as follows
public class SigletonTest {
private static volatile SigletonTest instance = null;
private SigletonTest() {
}
public static SigletonTest getInstance() {
synchronized (SigletonTest.class) {
// single check
if (instance == null) {
instance = new SigletonTest();
}
}
return instance;
}
}
But In case of the above code ,however, the first call to getInstance
So the first version is more efficient than second one.
- public class SigletonTest {
- private static volatile SigletonTest instance = null;
- // private constructor
- private SigletonTest() {
- }
- public static SigletonTest getInstance() {
- if (instance == null) {
- synchronized (SigletonTest.class) {
- // Double check
- if (instance == null) {
- instance = new SigletonTest();
- }
- }
- }
- return instance;
- }
- }
But The question is why the instance is null checked twice in line no 7 and line no 10.It seems it is sufficient to check the instance as null once after synchronization block.The code as follows
public class SigletonTest {
private static volatile SigletonTest instance = null;
private SigletonTest() {
}
public static SigletonTest getInstance() {
synchronized (SigletonTest.class) {
// single check
if (instance == null) {
instance = new SigletonTest();
}
}
return instance;
}
}
But In case of the above code ,however, the first call to getInstance
()
will create the
object and all the threads trying to access it during that time
need to be synchronized; after that all calls just get a reference to
the member variable. Since synchronizing a method could in some extreme
cases decrease performance . The overhead of acquiring and releasing a lock every time this method
is called seems unnecessary. Once the initialization has been completed,
acquiring and releasing the locks would appear unnecessary.So the first version is more efficient than second one.
No comments:
Post a Comment