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 14:40:04 +0100
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:0.9.8+) Gecko/20020202

Etienne M. Gagnon wrote:

I do not agree.  If I remeber correctly, this atomicity is only true
of "volatile" variables.  Otherwise, you have no garantee that the
integer value visible to one thread is the same as the one visible to
another on a multiprocessor system.

Be careful with such "micro-optimizations" which can be based on false
assumptions.  Let the compilers/VM do these optimizations.

First - removing as much synchronization as possible, while staying compatible is certainly a good thing. Synchronizing is _really_ costly - I remember one of my small programs using java.util.Random to run 4 times faster after removing 'synchronized' from few methods in this class. Of course this was uncompatible change, but if this could be done in compatible way, it is a clear win.

As for the Hashtable size(). Is there any point where it matters ?

a) all the rest of Hashtable is synchronized where needed and will access size correctly

b) code from outside has to synchronize on Hashtable externally anyway, if you want to make complex operations. It is perfectly ok to have

//A
if ( !map.isEmpty() )
{
   //B
   System.out.println(map.entrySet().iterator().next());
}

throwing no such element. Having isEmpty synchronized would allow us to catch changes made at point A, but not at point B. On the other hand, if you manually synchronized entire block (as it should be done), then at entry, A is propagated and at B no change can occur.

If you can show me an example, where having isEmpty()/size() synchronized _guarantees_ anything with fully preemptive threading, which is not guaranteed with unsynchronized version, then let it be your way. But I think that no such example can be given (but I would be happy to be proven wrong, as this would mean I do not understand some basic stuff with java threading).

Artur




reply via email to

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