Fair Issac Interview Question
Software Engineer / Developersclass Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
In multi threaded environment we are not sure the order of execution of statements
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
so that its better make helper variable as volatile, it will be visible for all threads
You can read the explanation from here:
- Billy G. April 14, 2009http://en.wikipedia.org/wiki/Double_checked_locking_pattern
Double-checked locking is actually OK as of Java 5 provided that you make the instance reference volatile.