[concurrency-interest] HalfSync
Jeremy Manson
jmanson at cs.purdue.edu
Wed May 24 17:15:42 EDT 2006
Hanson,
This isn't as thread safe as it would be if both were synchronized.
Consider the following program:
Initially, HalfSync hs = new HalfSync(0);
Thread 1:
while (hs.getCount() == 0) {
// do stuff
}
System.err.println("T1 Terminates");
Thread 2:
hs.increment(1);
System.err.println("T2 Terminates");
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.
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).
Jeremy
Hanson Char wrote:
> 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;
> }
> }
>
> As far as I can tell, this code is as thread-safe as it would be the
> case if
> both the increment() and getCount() are synchronized, but would allow
> higher
> level of concurrency. (Similar to CopyOnWriteArrayList).
>
> How would HalfSync compared to AtomicInteger ? Which one should perform
> faster ?
>
> Hanson
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
More information about the Concurrency-interest
mailing list