java hashset 同步,(Java)如果不同步,为什么允许HashSet同步使用?

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值