Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
user11406 Avatar asked Feb 22 '15 02:02

user11406


People also ask

Is a Java LinkedHashMap thread-safe?

Just like HashMap, LinkedHashMap is not thread-safe.

How is LinkedHashMap implemented in Java?

How LinkedHashMap Work Internally? Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster. Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.

Which is better HashMap or LinkedHashMap?

The Major Difference between the HashMap and LinkedHashMap is the ordering of the elements. The LinkedHashMap provides a way to order and trace the elements. Comparatively, the HashMap does not support the ordering of the elements.

Is ConcurrentHashMap put thread-safe?

ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications. At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap.


2 Answers

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
   }               
});
like image 188
Kevin Krumwiede Avatar answered Sep 21 '22 02:09

Kevin Krumwiede


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

like image 27
Evgeniy Dorofeev Avatar answered Sep 22 '22 02:09

Evgeniy Dorofeev