当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - Java Thread safe LinkedHashMap implementation?

问题描述:

I need to make use of the removeEldestEntry() method of LinkedHashMap.

What's the easiest way I make use of LinkedHashMap's and the removeEldestEntry() method in a thread safe way?

网友答案:

You can anonymously extend LinkedHashMap to change the behavior of removeEldestEntry(...), then wrap the instance of the anonymous class in a synchronized map. You didn't mention what type parameters you require, so I'm using <String, Integer> in this example.

Map<String, Integer> map = Collections.synchronizedMap(new LinkedHashMap<String, Integer>() {
   private static final long serialVersionUID = 12345L; // use something random or just suppress the warning
   @Override
   protected boolean removeEldestEntry(Entry<String, Integer> eldest) {
      return size() > MAX_SIZE; // how many entries you want to keep
   }               
});
网友答案:

java.util.Collections.synchronizedMap(map) returns a synchronized (thread-safe) map backed by the specified map.

分享给朋友:
您可能感兴趣的文章:
随机阅读: