3

There was a well-known pitfall while using the double-checked locking pattern (an example and explanation taken from "Concurrency in Practice"):

@NotThreadSafe
public class DoubleCheckedLocking {

private static Resource resource;

public static Resource getInstance() {
 if (resource == null) {
  synchronized (DoubleCheckedLocking.class) {
  if (resource == null)
    resource = new Resource();
  }
 }
 return resource;
}

}

Some thread may see the initialized value of 'resource' variable, while the object itself is still under construction.

A question is: is the problem remains if we are constructing the resource object in some method? I.e.

resource = createResource();

Can some thread evaluate resource != null as true while the resource object is still under construction in createResource() method?

MiamiBeach
  • 3,261
  • 6
  • 28
  • 54

2 Answers2

3

Yes, some thread can, or rather could. The code you posted works correctly these days. It was only with the earlier memory model (before Java 1.5) that the DCL pattern was flawed in.

Also DCL is obsolete these days since the best way to create a lazy loading singleton is with the singleton enum pattern.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

To answer your question, in the example you gave, the behaviour would not change if you were using a method or calling new directly. What affects behaviour between threads is a memory barrier of some type. A method dispatch is not enough.

However, double checked locking works as of Java 5, although you need to use the volatile keyword on on the instance. (To provide the memory barrier, as it happens.)

Why is volatile used in this example of double checked locking

Community
  • 1
  • 1
Darren Gilroy
  • 2,071
  • 11
  • 6