Last active
September 10, 2016 11:20
-
-
Save MaksimDmitriev/8e54add2107491dc8517387b18200bcc to your computer and use it in GitHub Desktop.
Broken multithreaded version. OK, why don't we just make the Helper field volatile?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DoubleFoo { | |
private volatile Helper d_helper; | |
public Helper getHelper() { | |
Helper result = d_helper; | |
if (result == null) { | |
synchronized(this) { | |
result = d_helper; | |
if (result == null) { | |
helper = result = new Helper(); | |
} | |
} | |
} | |
return result; | |
} | |
// other functions and members... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Broken multithreaded version | |
// "Double-Checked Locking" idiom | |
class Foo { | |
private Helper helper; | |
public Helper getHelper() { | |
if (helper == null) { | |
synchronized(this) { | |
if (helper == null) { | |
helper = new Helper(); | |
} | |
} | |
} | |
return helper; | |
} | |
// other functions and members... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because we don't want to enter the critical section if helper has been initialized