Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed size LinkedHashMap memory leak?

I'm trying to use LinkedHashMap as a local FIFO cache solution overwriting its removeEldestEntry method to keep size fixed:

Map lhm = new LinkedHashMap(MAX_CACHE_SIZE + 1, .75F, false) {
   protected boolean removeEldestEntry(Map.Entry eldest) {
      return size() > MAX_CACHE_SIZE;
   }
};

but when I constantly add new entries to the map monitoring process memory I see it keeps growing until max virtual machine memory is used though map size doesn't increase.

Is it by design? Why does it need more memory if old values are discarded and size of the map is limited?

UPDATE: as requested I'm attaching full code:

@Test
public void mapMemory() {
    final int MAX_CACHE_SIZE = (int) 1E3;
    Map lhm = new LinkedHashMap(MAX_CACHE_SIZE + 1, 1F, false) {
       protected boolean removeEldestEntry(Map.Entry eldest) {
          return size() > MAX_CACHE_SIZE;
       }
    };

    for (long i = 0; i < 1E10; i++) {
        lhm.put("key_" + i, "VALUE");
    }
}
like image 700
wziska Avatar asked Mar 03 '26 05:03

wziska


1 Answers

A blog post explaining memory leak issue with LinkedHashMap in multi-thread context

https://hoangx281283.wordpress.com/2012/11/18/wrong-use-of-linkedhashmap-causes-memory-leak/

like image 101
Hoang TO Avatar answered Mar 04 '26 20:03

Hoang TO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!