I am looking at some code in our app that I think may be encountering a case of "Double-checked locking". I have written some sample code that is similar to what we do.
Can anyone see how this can be experiencing double-checked locking? Or is this safe?
class Foo {
private Helper helper = null;
public Helper getHelper() {
Helper result;
synchronized(this) {
result = helper;
}
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
Base code borrowed from wiki.
It's unnecessarily complex, the simplest 'safe' way to do DCL is like so:
class Foo {
private volatile Helper helper = null;
private final Object mutex = new Object();
public Helper getHelper() {
if (helper == null) {
synchronized(mutex) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
}
The key points here being:
this instance.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With