classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Avoiding locks


From: David Holmes
Subject: RE: Avoiding locks
Date: Wed, 30 Jul 2003 09:07:41 +1000

> As I understand it, if the proposal in JSR 133 is adopted,
> it will be sufficient to declare the result field "volatile" for
> conforming VMs.

No the result "field" is just a local variable - declaring it volatile
won't do anything. Sascha's code correctly defined foo as volatile.
There is actually no need for the use of the local "result" at all:

private volatile Object foo;

public Object getFoo() {

  if (foo != null) {
    // Fast path, taken after the first invocation of getFoo().
    return foo;
  }

  // Slow path, only used for the first invocation of getFoo().
  // However, several threads may simultaneously reach this point.
  synchronized (lock) {
    // recheck foo to see if we got here first
    if (foo == null)
      foo = createFoo(); // foo is never set anywhere else
    return foo;
  }
}

If you want to "avoid locks" correctly with respect to the memory
model, then all shared objects must be accessed via references
declared as either final or volatile. (or use the new atomic
instructions coming in JSR-166 :) )

David Holmes





reply via email to

[Prev in Thread] Current Thread [Next in Thread]