posted 19 years ago
Synchronization has gotten much faster with the latest JVMs, but there's not point in using it if you don't need it. If you know your Vector/Hashtable will be used by only one Thread, then use an ArrayList/HashMap instead.
But when you need thread-safe implementations, oftne you can get better performance using a class built with smarter synchronization. For example, ConcurrentHashMap in JDK 1.5 uses two locks (I'm extrapolating from Doug Lea's work on which it is based): one for reading and another for writing.
See, lookup up a key and getting the size of a HashMap are thread-safe by themselves, meaning any number of threads could be calling those methods without causing problems because they don't modify the structure. So the read lock is acquired when calling those methods, and it doesn't block other threads from acquiring the read lock.
When a thread needs to alter the object -- put(key, value) -- then it must acquire the write lock. To do so, all threads that have the read lock must release their hold before the write lock can be acquired. Once that happens, that thread gets the write lock, which blocks any other lock attempt, both read and write, giving the thread exclusive access while it adds a new key. Once done, it releases the write lock and it's back to normal. In fact, if it's just replacing the value for an existing key, it doesn't need the write lock, just the read lock.
This makes the CHM much more performant in the case of many readers and few writers. If the implementation is good enough, you can tune the locks by giving preference to threads based on whether they want to read or write.
As you can see, simple synchronization across the board on a class works, but it's suboptimal in most cases. Again, though, if you don't need it, why pay the price?