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?
Just like HashMap, LinkedHashMap is not thread-safe.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With