线程安全LinkedHashMap没有Collections.synchronized [英] thread safe LinkedHashMap without Collections.synchronized
问题描述
我正在使用LinkedHashMap,并且环境是多线程的,因此这个结构需要是线程安全的。在特定事件期间,我需要读取整个地图推送到数据库并清除所有。
I am using a LinkedHashMap and the environment is multi threaded so this structure needs to be thread safe. During specific events I need to read the entire map push to db and clear all.
大部分时间只写入此地图。此地图有50个条目限制。
Most of time only writes happen to this map. This map has a limit 50 entries.
我使用的是Oracle MAF,它没有Collections.syncronizedMap可用。那么,我需要在synchronized块中放置什么东西以确保写入和读取不会让我遇到concurrentModificationException等。
I am using Oracle MAF and it does not have Collections.syncronizedMap available. So, what are things I need to put in synchronized blocks to make sure writing and reading doesn't hit me concurrentModificationException etc
几个要求:
- 我需要像循环队列那样表现它,以便重写LinkedHashMap的removeEldestEntry方法。
- 我需要保留订单
推荐答案
那么,我需要在同步块中放置什么东西以确保写入和读取不会遇到我的concurrentModificationException等
So, what are things I need to put in synchronized blocks to make sure writing and reading doesn't hit me concurrentModificationException etc
所有方法调用都应该在同步块中。
Everything method call should be in a synchronized block.
棘手的是使用迭代器,因为你必须在迭代器的生命周期中持有锁。例如
The tricky one being the use of an Iterator, as you have to hold the lock for the life of the Iterator. e.g.
// pre Java 5.0 code
synchronized(map) { // the lock has to be held for the whole loop.
for(Iterator iter = map.entrySet().iterator(); iter.hashNext(); ) {
Map.Entry entry = iter.next();
String key = (String) entry.getKey();
MyType value = (MyType) entry.getValue();
// do something with key and value.
}
}
这篇关于线程安全LinkedHashMap没有Collections.synchronized的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!