[concurrency-interest] HalfSync

David Holmes dcholmes at optusnet.com.au
Wed May 24 18:26:05 EDT 2006


Jeremy writes:
> This isn't as thread safe as it would be if both were synchronized.
...
> Even if Thread 2 terminates, Thread 1 might not, because there is no
> happens-before edge from Thread 2's increment to Thread 1.  If getCount
> were synchronized, then Thread 1 would terminate if Thread 2 did.

Huh? count is volatile.

> The class would probably be a faster read than AtomicInteger, but a
> slower write (getting a lock is slower than performing a single atomic
> increment).

My 2c:
 - 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

Cheers,
David Holmes



More information about the Concurrency-interest mailing list