Detecting the memory consumption in Java to react on your code on it is not a good idea. You never know how the garbage collector behaves, when it is started and how often, how much memory it can free up, …
You could use a WeakReference (java.lang.ref) if you want to prevent that a reference to an object prevents that it can be removed by the garbage collector. But if you implement a cache, this could make the cache useless because your cached objects might be removed very quickly and to often.
I would propose to use an LRU-Cache. Such a cache has a certain capacity. If this capacity is exceeded, the least recently used elements will kicked out of the cache. This prevents in a simple way, that you cache can grow infinitely.
You can find some simple implementations if you google for it:
public class LRUMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int capacity;
public LRUMap(final int capacity) {
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
If you need more I would check for existing cache implementations. They might support additional configuration capabilities like e. G. maximum age for an entry of you cache.