Java concurrent exception in the synchronized collection

来源:互联网 发布:笑笑西卡淘宝店 编辑:程序博客网 时间:2024/05/21 07:59

I met a java concurrent exception in the synchronize collection few days ago.

 

Case:

In case a thread do the add/remove on this collection and another thread do the iterate

at same time. It will throw this exception.

 

Fix:

Way1:

Transfer it to array.

--- [instance of hashtable].values().toArray()

Due to [collection]=[hashtable].values() share the same synchronized instance key with instance of

this [hashtable], so toArray() method will be thread safe.

 

way2:

Synchronize [instance of hashtable] before the iterate operation.

原创粉丝点击