KeyFMap (@NotNull KeyFMap map) { if (!shouldIntern(map)) { return map; } MapReference key = new MapReference(map); synchronized (cache) { MapReference internedKey = cache.addOrGet(key); if (internedKey == key) { // was not present - no need to move to last, remove old items while (cache.size() > MAX_SIZE) { cache.removeFirst(); } return map; } else { // use the interned map if still actual KeyFMap cached = internedKey.get(); if (cached == null) { // weak reference was collected - remove item cache.remove(internedKey); cache.add(key); return map; } else { // was present and actual - move to last cache.addAndMoveToLast(internedKey); return cached; } } } }