Is it safe to close object before removing it from LinkedHashMap?

269 Views Asked by At

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;
        }
2

There are 2 best solutions below

0
On

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
On

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.