«« 0.2.0 Update Selecting with SWT Table and JFace TableViewer »»
blog header image
Is a Hashtable of <String, Vector> Threadsafe?

I have a Java question but here's some background first. A Vector and an ArrayList both implement the List interface except a Vector is threadsafe because it has synchronized methods. Likewise, a Hashtable is a threadsafe implementation of the Map interface and HashMap is its thread unsafe compadre.

ArrayList and HashMap exist because synchronized methods are expensive. So if you just need a Map and you're not going to use more than (the) one (main) thread then you can get a performance boost from HashMap.

So here's the question: If I have a Hashtable where the keys are Strings and the values are Vectors of immuatable objects, is that threadsafe? I'm guessing probably not because all of the methods that manipulate this structure extract a Vector from the Hashtable, add or remove objects and then replace the Vector in the HashTable where it was. It looks like I'm going to have to make all of the mutator methods synchronized and take the performance hit.

Speaking of threads, I'm probably going to pick up Taming Java Threads by Allen Holub soon. Has anyone used this book?

Posted at February 11, 2004 at 09:24 PM EST
Last updated February 11, 2004 at 09:24 PM EST
Comments

You will have to use synchronized methods if you want to do this.
However, the bigger question is whether you really need something like this. If only one object at a time will be changing the Vector contents then there is no problem, you will not need this. This is usually the case when the manipulation depends on a user. Example: the Vector of songs needs to be modified on a mouse event. There is only one object trying to modify the Vector at a time, so there is no problem.
If you really must do this, then have synchronized methods and go back to HashMap and ArrayList, instead of Hashtable and Vector, since you provide the protection now.

» Posted by: Aleks at February 11, 2004 11:09 PM

Ahh, good point. If I synchronize from the outside I can use HashMap and ArrayList on the inside. No sense doubling up the synchronized methods. Excellent.

» Posted by: Ryan at February 11, 2004 11:16 PM
Google
 
Search scope: Web ryanlowe.ca