Not sure what you want clarified, so apologies if I explain the wrong thing:
RE: most field read/writes are atomic: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.7
RE: there is still a race condition: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4
I've done a fair bit of multi-threaded programming. The C/C++ and Java language specs give compilers a fair amount of latitude in reordering and optimizing code. This destroys many idioms that folks think eliminate the need for explicit synchronization. And it's real hard to debug these. Took me near two weeks to find the premature end of a critical section. The author had terminated it one statement early because he thought it was safe due to a trick he was using. Compiler undid his trick.
A lesson I've learned, painfully, is do not optimize away critical sections unless: 1) A performance analysis shows it is important. Really important. 2) You really know what you are doing. Criteria one is not met in this case, there's no good reason to eliminate using synchronized.
Alternatively, consider using java's atomic classes: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html
On Jun 12, 2012, at 5:19 AM, Dennis German wrote:
> Could you please provide an addition explanation for:
> > ... Memory reads/writes are indeed atomic. Well most of them ;-> ...
> > Admittedly, the hole is tiny. Very tiny.
> > Even if executed in a tight loop it may trip only once every 10-20 minutes.
> > In this case, folks may see it only very, very rarely. t ...
> > giuliano
> Developers mailing list
Developers mailing list