Can I limit the HashMap to the amount of memory it occupies?

I use simple cache with help LinkedHashMapbased on found commands here . I am using the following code:

public class Cache extends LinkedHashMap {
  private final int capacity;

  public Cache(int capacity) {
    super(capacity + 1, 1.1f, true);
    this.capacity = capacity;
  }

  protected boolean removeEldestEntry(Entry eldest) {
    return size() > capacity;
  }
}

It is very simple. However, it simply imposes a fixed size on the card. I work on a very small heap, and depending on the size of the cached objects and my selected capacity, this can still end up without memory. The objects are arbitrary, so I can’t appreciate how big they are. I don’t want to depend on SoftReferencesto crop the cache, because the cleaning method is unreliable; it changes from VM to VM, and they can either be fixed too soon, or they can never be fixed until they fill my heap.

?

+3
4

/ , 2 () :

1) Java, , . "" , ( !)., - , .

2) JMX GC . . "" MemoryMXBean javadoc.

+3

, , "" . (.. put(), copy-constructor ..), , ( , Java?). , , , / . ?

http://www.javapractices.com/topic/TopicAction.do?Id=83

+2

You can wrap the implementation Mapand apply size in putand methods putAll.

0
source

Source: https://habr.com/ru/post/1757024/