Re: unable to synchronize on primitive wrapper class?
Lew wrote:
Lew wrote:
Also, there is no synchronization on 'count' whatsoever.
Roger Lindsj? wrote:
That should not matter since each thread gets its own Worker, and
count is not static. The problem is well described by Eric, the
threads keep synchronizing, but on different Integer objects.
It is a concern because the count variables are referenced from the
main() thread without synchronization. When a variable escapes its
thread, synchronization issues can arise.
From the OP:
System.out.println(t1 + ".count=" + w1.count + "\n" +
t2 + ".count=" + w2.count + "\n" +
"total="+ Worker.total + "\n" +
"DIFF=" + (w1.count+w2.count-Worker.total));
There are two references each to w1 and w2 from main(), outside the
threads that are calculating these values. These values very well could
change from main()'s point of view between successive invocations.
I'd strike "very well" because of the Thread.sleep(50) call
before main() accesses the threads' count variables. On most
machines nowadays, fifty milliseconds is a very long time, and
the two threads should have ample opportunity to realize that
they've been interrupted and cease operation.
The "could" should stand, though, since delaying is no
substitute for proper synchronization (e.g., calling join() on
both threads). Still, the race on the counts is probably not
the cause of the behavior the O.P. reports.
--
Eric Sosman
esosman@ieee-dot-org.invalid