Wednesday, May 24, 2006
HalfSync
It seems we can easily construct something which is simple, thread-safe, and yet competitive to or even faster than j.u.c.a.AtomicInterger!
Consider the code:
Interesting comments by David Holmes:
Consider the code:
// Only the write is synchronized, not the read
public class HalfSync {
private volatile int count;
public HalfSync(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public synchronized int increment(int delta) {
return this.count += delta;
}
}
Interesting comments by David Holmes:
"- reads: same
both do a LD with whatever memory barrier is needed on the
platform (which is probably none)
- writes:
- uncontended: close call
AtomicInteger.get has a method call with LD and CAS plus MEMBAR
Half-sync: CAS for synchronized, LD, ST plus MEMBAR (depends if
the runtime elides the redundant MEMBARS for sync+volatile
- contended: Half-sync wins by avoiding ctx switches"
Monday, May 15, 2006
j.u.c.atomic.Atomic*.weakCompareAndSet
I have been wondering what it means when it "fails spuriously" in invoking those weakCompareAndSet methods in Java 5, and what a good use case would be like. It turns out the spurious "failure" simply means the method would do nothing and return false for no apparent reason.
Sample Usage:
Sample Usage:
As commented by Doug Lea:public class Foo {
private volatile int latency = -1;
private final AtomicInteger maxLatency = new AtomicInteger(-1);
public void setLatency(int latency)
{
this.latency = latency;
updateMaxLatency(latency);
}
private void updateMaxLatency(int latency)
{
for (;;) {
int maxLatencySnapshot = this.maxLatency.get();
if (latency > maxLatencySnapshot)
{
if (!this.maxLatency.weakCompareAndSet (maxLatencySnapshot, latency))
// race condition or just fail spuriously; so let's retry
continue;
}
return;
}
}
// ...
}
"Yes, this is fine; it is a good example where either the plain or the weak form would work just as well, so you might as well use the weak form."Special thanks to David Holmes for his generous and thorough explanation.