Tuesday, 10 September 2013

Bull Pugh method of implementing Singleton resulting in "Out-of-order Write"?

Bull Pugh method of implementing Singleton resulting in "Out-of-order Write"?

I went through Bull-Pugh's method of implementing Singleton design pattern
in Java.
I have a concern regarding it. Please correct me if I am wrong anywhere.
Please consider the below Bull-Pugh code:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of
Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
// Line 10
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE; // Line 14
}
}
Consider "Thread-1" has called "return SingletonHolder.INSTANCE;" on
Line-14 for the first time. Now the Singleton class will be instantiated
on Line-10.
Before this instantiation is complete, let us say that "Thread-1" is
preempted by an another thread- "Thread-2". When "Thread-2" calls "return
SingletonHolder.INSTANCE;" on Line-14, WILL IT RETURN PARTIALLY
CONSTRUCTED OBJECT?
If it returns a partially constructed object, this situation will be an
"Out-of-Order Write". Please let me know if I am correct on the above case
and share your thoughts. Also please let me know if this situation can be
overcome by any other means. Thanks in advance.

No comments:

Post a Comment