4

I want to override LinkedHashMap's removeEldestEntry(Map.Entry) method to remove stale mappings automatically. Also I want to cleanup the entry that would be removed.

The entry is an AutoCloseable object. Can I call close() on it if it's going to be removed? Is it the best practice to do it as below?

        public boolean removeEldestEntry(@Nonnull final Map.Entry<myKey, myObject> eldestEntry) {
            if (size() > 100) {
                eldestEntry.getValue().close();
                return true;
            }
            return false;
        }
eriee
  • 416
  • 2
  • 15
  • I don't see why not. The calling code is pretty straightforward, basically `if (removeEldestEntry(eldest)) removeEntryForKey(eldest.key);`. And the spec even allows it to modify the map if necessary. – shmosel Sep 26 '18 at 18:10
  • 1
    Why are you using a raw `Map.Entry`? – user2357112 Sep 26 '18 at 18:31
  • I think you have true and false flipped: right now you evict entries _unless_ there's over 100 of them. – Louis Wasserman Sep 26 '18 at 18:57
  • @LouisWasserman oops i will change it. thanks. – eriee Sep 26 '18 at 19:51
  • As user2357112 says, instead of using raw types it's safer to use generic parameters (``) on your LinkedHashMap-derived class, and then the `eldestEntry` argument will be of type `T` and you can omit the cast when calling `close()`. – Klitos Kyriacou Oct 04 '18 at 20:29
  • I generated the override method in IntelliJ. Changed it with type. Thanks! – eriee Oct 04 '18 at 20:40

2 Answers2

1

If you are no longer using any of the underlying resources and have no need for the item, I do not see why not.

0

Closing a resource doesn't free the object or make it unsafe to use.

It might throw an exception if you try to use it after closing it depending on what the methods you call do on a closed resource.

An object's memory is only freed on a GC when the object is no longer referenced.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130