Jeu George’s Weblog

Life in the fast lane

Son of a Bug

Posted by Jeu George on June 16th, 2006

This was one of the earliest and probably one of the more frustating bugs I worked on. It was my first job and probably around six months into it. printf was still my favorite debugging tool, and was still getting the hang of  debuggers. My task was to improve the performance of Connection pool manager in the JDBC driver I was working on at the time. A section of this code implemented the singleton pattern, and one of the taskitems was to change the regular implementation to the Double Checked Locking Mechanism. I thought this was a pretty clever idea, but it kept breaking and I couldn’t figure out the reason for the longest time. The funny thing was that I couldn’t reproduce this under the debugger and neither were my printf’s (System.Writeline) or colleagues of any help and that made it even more frustating.

I eventually decided not to go ahead with this obviously, but I was glad to know the reason(s) when I finally knew it.

One of the explanations attributed it to a bug in the Java Memory Model (Out of memory writes).

1: public static Singleton getInstance()
2: {
3:   if (instance == null)
4:  {
5:    synchronized(Singleton.class) { 
6:      if (instance == null)         
7:        instance = new Singleton();
8:     }
9:   }
10:   return instance;
11: }

You would expect Line 7 to be atomic, but in fact you can break this up into

7.1 mem = allocateMemory();       //Allocate memory for Singleton object.
7.2 instance = mem;               //Note that instance is now non-null, but has not been initialized.
7.3 ctorSingleton(instance);      //Invoke constructor for Singleton passing instance.

In a multithread environment, you can guess what would happen after one thread loses its time slice after executing Line 7.2

 The other explanation that I heard was that the compiler would get ’smart’ and realize that there was nothing really useful between Lines 3 and 6 and nothing changed the value of the instance variable in between, and so it would ‘optimize’ the code by taking out Line 6 and combining it with Line 3. In Debug mode, it wouldn’t ‘optimize’ this and it worked like a charm.

There have been a ton of discussion around this, a good amount of which is captured here.

Sources for sources:

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>