dcsimg
What is double-checked locking? Does it work?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Alex_Chaffee
Posted On:   Friday, November 23, 2001 01:54 PM

Double-checked locking (DCL) is an idiom recommended by a number of Java books and articles as a way to reduce synchronization overhead when performing lazy initialization. The DCL idiom was designed to support lazy initialization, which occurs when a class defers initialization of an owned object until it is actually needed. Unfortunately, DCL isn't guaranteed to work under the current Java Memory Model (JMM). See the following articles by Brian Goetz (from which this FAQ answer is excerpted): Double-checked locking: Clever, but broken Can double-checked locking be fixed? Can ThreadLocal solve the double-checked lo   More>>

Double-checked locking (DCL) is an idiom recommended by a number of Java books and articles as a way to reduce synchronization overhead when performing lazy initialization.


The DCL idiom was designed to support lazy initialization, which occurs when a class defers initialization of an owned object until it is actually needed.


Unfortunately, DCL isn't guaranteed to work under the current Java Memory Model (JMM).


See the following articles by Brian Goetz (from which this FAQ answer is excerpted):



Briefly, the following single-checked code is thread-safe:

			
				
class SomeClass {
private Resource resource = null;

public synchronized Resource getResource() {
if (resource == null)
resource = new Resource();
return resource;
}
}

but the following double-checked code is faster, but thread-unsafe:
			
				
class SomeClass {
private Resource resource = null;

public Resource getResource() {
if (resource == null) {
synchronized {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}

In my (Alex's) humble opinion, the whole debate is misguided and somewhat moot: you should just trust the JVM to make synchronized as fast as possible. Furthermore, if the bottleneck in your code is instance variable initialization, then it's probably *not* instance variable access (and vice versa).    <<Less

Re: What is double-checked locking? Does it work?

Posted By:   Alex_Chaffee  
Posted On:   Thursday, November 29, 2001 09:23 AM

foo
About | Sitemap | Contact