max wrote:
since writes are synchronized the data will always be 100% correct - but you might have read the value 1 milisecond before it was updated, and that would also happen if read was synchronized.
Doug Lea wrote this to me about this topic:
==================
It is just plain wrong. A JVM is allowed to reorder/cache
per-thread reads unless they are loaded under sync or
are volatile (or also, java.util.concurrent.atomic's). So
a reading thread can see an arbitrarily old value. In fact
it can always return zero to any thread that did not itself
update it. JVMs tend not to exploit this as much as they are
allowed to, so it will often look like it works, but is still
wrong.
BTW, Normally the best way to create thread-safe counters in
J2SE5+ is AtomicInteger/AtomicLong, using getAndIncrement.
-Doug
=================
Doug Lea is the foremost expert in the field of concurrency.
Dino