A Java Challenge: Why Doesn't This Work?

Status
Not open for further replies.

Midlands

Ars Praetorian
535
Subscriptor
This is probably the single most difficult question I know of with respect to Java programming. I've never met a single person who can answer it who hasn't already seen it before -- and I work with some scary-smart Java hackers.

So the problem is as follows. You have a singleton class (only one instance ever can exist), and you'd like to not initialize it until you actually need it (lazy initialization). Furthermore, it needs to be thread-safe, so that if multiple people try to grab it at the same time, you only allocate one instance. So you start out with:

code:<HR>
Code:
public class Foo {
  private static Foo instance = null;
  public static synchronized Foo getInstance() {
    if (instance == null) instance = new Foo();
    return instance;
  }
}

That works great. However, you'd like to avoid the hit of the synchronization every time you call getInstance() -- it's a lot of overhead to pay each time.

Can you do this safely? If so, how? If not, why not?
 
I've never met a single person who can answer it who hasn't already seen it before -- and I work with some scary-smart Java hackers.

So can you answer it? Anyhow...

code:<HR>
Code:
public class Foo {
    private static Foo instance = new Foo();<P>    public static Foo getInstance() {
        return instance;
    }
}

or if your need something a little more complicated...

code:<HR>
Code:
public class Foo {
    private static Foo instance;<P>    static {
        String monkey = "blah";
        instance = new Foo(monkey);
    }<P>    public static Foo getInstance() {
        return instance;
    }
}

If neither of those are what you're looking for, I'm pretty sure it can't be done. I'm guessing most people don't know about the static block trick.

~Kevin
:)
 
That isn't lazy initialized, which you can't apparently do without incurring the synchronization overhead each and every time, because the VM can make the reference non-null before it's constructed the object to which it refers, which seems pretty assinine.

Assigning it to a temporary variable and then assigning it to the real variable certainly ought to be performed atomically, and certainly ought to leave the reference null until it's constructed.
 

Midlands

Ars Praetorian
535
Subscriptor
Anyway, I didn't mean to sound arrogant in my original post. This one just blew my mind when I first read about it, and I'd been using the idiom (double-checked locking) all the time. (And no, I didn't have a chance in hell of explaining this before someone explained it to me. So, in other words, I *couldn't* answer it. ;-) )

It's one of those things whose underlying reasons are esoteric as all hell, but which bites a very common pattern right in the ass.

There are actually fairly valid reasons it's set up like this -- specifically, a lot of RISC chips (including the Alpha and UltraSPARC) have very-high-performance memory-model modes that you can use that behave like this in hardware, and if Java's defined this way, then you can validly run all Java programs under that memory-model model.

I wish they'd make this more public. It does, in fact, actually happen, especially on Alphas.
 
Assigning it to a temporary variable and then assigning it to the real variable certainly ought to be performed atomically,

There are few things guaranteed to be atomic in the Java VM, but they aren't as much of a "sure thing" as you might think. Only 32 bit assignments are, but exact bit size is not guaranteed by the language - only ranges are guaranteed. It must be declared volatile or be withing a synch block to be guaranteed.


Read the section in the page below:


Myth 3: Atomic operations are thread safe
http://www6.software.ibm.com/devtools/news1001/art24.htm
 
code:<HR>
Code:
<P>public class ThreadSync extends Thread {<P>    private int value;
    public ThreadSync(int v) {
        value = v;
    }<P>    public void printValue(int v) {
        synchronized {
            while (true) {
                System.out.println(v);
            }
        }
    }<P>    public void run() {
        printValue(value);
    }<P>    public static void main(String[] args) {
        new ThreadSync(1).start();
        new ThreadSync(3).start();
    }
}

Wait, does this actually compile for you guys? I just gave it a shot and it didn't.

code:<HR>
Code:
ThreadSync.java:10: '(' expected
                synchronized {
                             ^

However, when I changed the block to

code:<HR>
Code:
synchronized (ThreadSync.class) {

Everything compiled just fine. javac doesn't want to give me a version number but java -version reports

code:<HR>
Code:
java version "1.3.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_01)
Java HotSpot(TM) Client VM (build 1.3.1_01, mixed mode)

This is the GNU/Linux version, btw.

~Kevin
:)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by abamfici:
Wait, does this actually compile for you guys? I just gave it a shot and it didn't.

It shouldn't. The synchronized statement in Java is:

<SynchronizedStatement> ::= synchronized ( <Expression> ) <Block>

Perhaps you meant:

code:<HR>
Code:
public void printValue(int v) {
  synchronized (this) {
    while (true) {
      System.out.println(v);
    }
  }
}

If you want the printValue method synchronized per ThreadSync object. Or maybe you want what you wrote if you intend that it is synchronized on the Class object representing ThreadSync.

If it's the former, then:

code:<HR>
Code:
public synchronized void printValue(int v) {
  while (true) {
    System.out.println(v);
  }
}

Is an equivalent form.

(kg*m*m)/(s*s)
 
newton_meter:

Well, both of the articles slam on using naked synchronize blocks

code:<HR>
Code:
class SomeClass {
  private Resource resource = null;<P>  public Resource getResource() {
    if (resource == null) {
      synchronized {
        if (resource == null) 
          resource = new Resource();
      }
    }
    return resource;
  }
}

in http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double-test.html

and

http://www6.software.ibm.com/devtools/news1001/art24.htm#toc4

mentions it in words. The first article never mentions what will happen if the code looks like so..

code:<HR>
Code:
class SomeClass {
  private Resource resource = null;<P>  public Resource getResource() {
    if (resource == null) {
      synchronized (resource) {
        if (resource == null) 
          resource = new Resource();
      }
    }
    return resource;
  }
}

Which looks to me like it might work as expected. The compiler/jvm is free to reorganize for speed as long as there is same end result, but it looks to me like resource will only be flushed back to main memory after it's fully new'ed avoiding the problems the article mentions. Or perhaps it's broken in the same way the volatile solution is... ??? How about declaring resource to be volatile in addition to sychronizing on it?

Was the grammar changed to prevent boneheaded usage of synchronized?

~Kevin
:)
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by abamfici:
Well, both of the articles slam on using naked synchronize blocks

They do? I've never heard of such a thing, and couldn't find any reference to it in the Java Language Specification (First or Second Edition).

The first article contains a typo. The code should be:

code:<HR>
Code:
class SomeClass {
  private Resource resource = null;<P>  public Resource getResource() {
    if (resource == null) {
      synchronized (this) {
        if (resource == null) 
          resource = new Resource();
        }
      }
    return resource;
  }
}

The second article shows a synchronized method (in Listing 3), and a block synchronized on a Class object (in Listing 4). No synchronized blocks that are "implicitly" synchronized on some object. How would the compiler know what you intended?

The first article never mentions what will happen if the code looks like so..

code:<HR>
Code:
class SomeClass {
  private Resource resource = null;<P>  public Resource getResource() {
    if (resource == null) {
      synchronized (resource) {
        if (resource == null) 
          resource = new Resource();
      }
    }
    return resource;
  }
}

Null pointer exception. How can you synchronize on an object that isn't there? null is a reference to no object, and "no object" doesn't have a lock to synchronize on.

The relevant section is 14.18 in the language spec (2nd Edition).

Which looks to me like it might work as expected. The compiler/jvm is free to reorganize for speed as long as there is same end result, but it looks to me like resource will only be flushed back to main memory after it's fully new'ed avoiding the problems the article mentions. Or perhaps it's broken in the same way the volatile solution is... ??? How about declaring resource to be volatile in addition to sychronizing on it?

The original "Double Checked Locking Idiom..." declaration is at Bill Pugh's web site. The point is, nothing does what the original poster wants, until the new memory model is finalized and implemented.

(kg*m*m)/(s*s)
 
Status
Not open for further replies.