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

孤街醉人 提交于 2021-01-27 07:43:36

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/47563169/java-why-is-a-hashset-allowed-to-be-used-synchronously-if-it-is-non-synchroniz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!