classpath
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: java.util.Hashtable.size()/isEmpty()


From: Artur Biesiadowski
Subject: Re: java.util.Hashtable.size()/isEmpty()
Date: Fri, 15 Feb 2002 17:53:40 +0100
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8+) Gecko/20020202

Eric Blake wrote:
No - even accessing a simple field must be synchronized, for this
reason:

Suppose thread A is in the middle of calling clear() when thread B calls
size().  Notice in clear() that the size is not changed until after all
entries have been set to null, meaning that B will read a larger size
than what is actually there.  For thread safety reasons, if you have a
synchronized object, EVERY public access point to information on that
object must be synchronized.

No,no,no.

Thread B could as well read the value from before clear happens. If it does not synchronize, there is not such thing as 'while A is middle of clear'. This two things does not happen in sequence - you have to think about them as about quantum physics - all possible cases.

So if we have A thread calling synchronized clear and B thread calling unsychronized size, B can return either previous size or 0 or even some value from long,long time ago - _regardless_ of sequence of evens that happened physically in processor. This is allowed behaviour.

If clear would remove element after element, then indeed, size would have to be synchronized - because it could report map having for example half elements (whereas it never happened - first it has n elements and then 0, because clear is atomic). BUT as clear update size atomically (regardless of synchronization), there is not need to also synchronize getter.

Artur




reply via email to

[Prev in Thread] Current Thread [Next in Thread]