[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Avoiding locks
From: |
Sascha Brawer |
Subject: |
Avoiding locks |
Date: |
Tue, 29 Jul 2003 17:52:41 +0200 |
Hi all,
vaguely related to the current thread about "Thread/VMThread proposal" on
the Classpath discussion list, I would like to ask whether the following
pattern is correct with respect to the Java memory model. I believe so,
but I would like to be sure.
// foo is initially null; only set by the first invocation of getFoo()
private volatile Object foo;
public Object getFoo()
{
Object result = foo;
if (result != null)
{
// Fast path, taken after the first invocation of getFoo().
return result;
}
// Slow path, only used for the first invocation of getFoo().
// However, several threads may simultaneously reach this point.
synchronized (lock)
{
// If threads are competing for the lock, the winner of the
// race will see (foo == null), and the losers (foo != null). The
// losers just return the foo which was created by the winner.
if (foo == null)
foo = createFoo(); // foo is never set anywhere else
return foo;
}
}
The point of this is to avoid monitorenter/monitorexit after the first
invocation of getFoo(). It certainly makes the code hard to read, so I
would use this only at very carefully selected places (in gnu.java.awt.font).
Thanks for the clarification,
-- Sascha
Sascha Brawer, address@hidden, http://www.dandelis.ch/people/brawer/
- Avoiding locks,
Sascha Brawer <=