(Java) Why is a HashSet allowed to be used synchronously if it is non synchronized?

Question

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?


Show source
| java   | multithreading   | synchronous   | synchronization   | hashset   2017-11-29 23:11 1 Answers

Answers to (Java) Why is a HashSet allowed to be used synchronously if it is non synchronized? ( 1 )

  1. 2017-11-29 23:11

    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).

Leave a reply to - (Java) Why is a HashSet allowed to be used synchronously if it is non synchronized?

◀ Go back