I've been reading up on the differences between a HashMap, HashSet, and HashTable. A key thing I've been noticing is that I've seen that HashMap/HashSet are not synchronized while a HashTable is.
However in a code base that I've seen before there are several places where a block like this is used:
synchronized (hashSet) {
//Some code involving the hashset
}
How is this possible if a HashSet isn't synchronized? Does the synchronized block simply allow us to use a non synchronous data structure as if it were synchronized?
If HashSet were synchronized would we just not have to include the synchronized() {} block?
解决方案
A synchronized block requires some object to syncronize upon. When a HashSet is said to be unsynchronized it just means that it's methods aren't synchronized in their own right, and if you intend to use it in a multi-threaded context, you should handle synchronization by yourself (e.g., by synchronizing on the HashSet object as shown in your snippet).