Google
 
Web unafbapune.blogspot.com

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:
// 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"

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?