Skip to content

Instantly share code, notes, and snippets.

@MaksimDmitriev
Last active September 10, 2016 11:20
Show Gist options
  • Save MaksimDmitriev/8e54add2107491dc8517387b18200bcc to your computer and use it in GitHub Desktop.
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?
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...
}
// 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...
}
@MaksimDmitriev
Copy link
Author

Because we don't want to enter the critical section if helper has been initialized

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment