Home > Java > Double Checked Locking and JSR 133

Double Checked Locking and JSR 133

November 19th, 2006

I have, like many others used the Singleton pattern many times. Each time, again like many others, I have been annoyed of the synchronized getInstance() method when using lazy instantiation. I then came across the Double Checked Locking (short: DCL) method that handles exactly that by amazing simplicity. It worked! But it is broken. To really understand why, you should take a look at the Java Memory Model (short: JMM) and the JSR133 that fixes it. The problem is basically caused by the JVM being able to do byte reordering as I understand it. This changes the execution flow of instructions. Many people has written about the DCL problem but few using the DCL code has encountered a real problem, never the less you shouldn’t use it prior to version 5 of Java. This is because the JSR 133 wasn’t part of the JVM until then.

Now to the good news: DCL does work in Java 5.

Yes, from version 5 it can work. The only thing you have to do is to make the instance field volatile. Unofficially this should also work in Java 1.4 but I haven’t found any real evidence.

Should I use DCL ?

In my opinion no, and I’ll tell you why
DCL will still be questioned by many
Synchronization has gotten a lot cheaper.
You can’t be sure your JVM is Java 5 (forget class versions)

Of cause, all this isn’t a issue if you didn’t do lazy instantiation.

JSR133
http://www.jcp.org/en/jsr/detail?id=133

Fixing the Java Memory Model, Part 1
http://www-128.ibm.com/developerworks/library/j-jtp02244.html

Fixing the Java Memory Model, Part 2
http://www-128.ibm.com/developerworks/java/library/j-jtp03304/

JSR 133 (Java Memory Model) FAQ

http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

The JSR-133 Cookbook for Compiler Writers
http://gee.cs.oswego.edu/dl/jmm/cookbook.html

Double-checked locking and the Singleton pattern
http://www-128.ibm.com/developerworks/java/library/j-dcl.html

The (old) Java Memory Model is Fatally Flawed
http://www.cs.umd.edu/~pugh/java/broken.pdf

Benjamin Sølberg Java

  1. November 24th, 2006 at 14:59 | #1

    Follow up:
    Here is a code example on the correct use of DCL in Java 5:
    Please note that the _foo field is volatile!

    public class Foo {
        private static volatile Foo _foo = null;
    
        public static Foo getInstance() {
            if (_foo == null) {
                synchronized (Foo.class) {
                    if (_foo == null) {
                        _foo = new Foo();
                    }
                }
            }
            return _foo;
        }
    }
  1. No trackbacks yet.