Anupam Sinha wrote:Can getSize always return 0 for the current code? Doesn't synchronize also provides a happens before guarantee?
If
two threads synchronize on the same object you have your guarantee, so if two threads both 'add' it works but if another thread calls just getSize looking for objects to work with say it potentially doesn't :-( ie another thread could just call getSize and never sync at all.
In some edge cases the synchronized key
word can be optimized away by
Java i.e. if it can tell no other thread will ever contend, it was a common misconception that adding synchonized guarantees a memory barrier.
The add method has a read/write barrier but getSize has none at all so you have to work out the last sequence point for the two threads. The thread calling getSize may have effectively cached the size of the collection at zero in theory forever however changing getSize to synchronized prohibits any compiler optimization, caching etc etc i.e. its a volatile read the add method being a volatile write on its own may not be enough.
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5