aspose file tools*
The moose likes Threads and Synchronization and the fly likes Double checked locking Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Double checked locking" Watch "Double checked locking" New topic
Author

Double checked locking

Kalyan Anand
Ranch Hand

Joined: Feb 07, 2007
Posts: 194
Java 1.4 and prior to that Double checked locking was broken but I heard sometime ago that from Java 1.5 it was fixed.

Now what is the general opinion on DCL given that I will have to use only synchronized keyword and no concurrent API.
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

Double-Checked Locking can be implemented in Java 5, if you do it just right. The general opinion seems to be that there are better ways to do it, though.

See http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html.
victor kamat
Ranch Hand

Joined: Jan 10, 2007
Posts: 247
The code below will work; not that I made Helper volatile.
Effective Java 2nd edition ( Bloch ) has a nice section on this.

class Foo {
private volatile static Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null)
helper = new Helper();
}
return helper;
}
}
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

This is a well known problem, and most of the "fixes" don't work.
See
http://www.ibm.com/developerworks/java/library/j-dcl.html
Kalyan Anand
Ranch Hand

Joined: Feb 07, 2007
Posts: 194
Originally posted by Pat Farrell:
This is a well known problem, and most of the "fixes" don't work.
See
http://www.ibm.com/developerworks/java/library/j-dcl.html


The article you posted refers to 1.4 and prior. With 1.5 it is fixed. My questions was is there any valid reason NOT TO GO for DCL in Java 1.5
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1836
    
    7

http://www.coderanch.com/t/100824/patterns/singleton-query


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Kalyan Anand
Ranch Hand

Joined: Feb 07, 2007
Posts: 194


What you mean by lazy initialization holder approach ?
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1836
    
    7



This ensures that Foo is lazily initialized when the getFoo() method is first called, because of the implications of the static keyword in the context of class initialization. Also, because of static initilization there's no need for synchronization. See the JLS for more details, because these are all the details I remember, having read Java Concurrency in Practice a good while ago.
[ September 11, 2008: Message edited by: Jelle Klap ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double checked locking