Java concurrent exception in the synchronized collection

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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章