Secure LinkedHashMap implementation in Java Thread?

I need to use the removeEldestEntry() LinkedHashMap .

In what simple way do I use LinkedHashMap's and removeEldestEntry() method LinkedHashMap's safe thread?

+7
java hashmap multithreading thread-safety
source share
2 answers

You can anonymously extend LinkedHashMap to change the removeEldestEntry(...) behavior, and then transfer the instance of the anonymous class to the synchronized map. You did not specify what type parameters you need, so I use <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 } }); 
+9
source share

java.util.Collections.synchronizedMap (map) returns the synchronized (thread safe) card supported by the specified card.

+4
source share

All Articles