Should we always free up Map or List in Java?

Viewed 68

Let's say I have a Map. I added a couple of elements, processed those elements and now I no longer need those elements. Should I call Map#clear(); method or just let garbage collector do its job? Does cleaning the map reduces GC pressure?

Here is a sample code:

    public void process() {
        Map<String, Object> myMap = new LinkedHashMap<>();
        myMap.put("CatA", "Meow1");
        myMap.put("CatB", "Meow2");

        doSomeProcessing(myMap);

        myMap.clear();
    }

P.S- This operation will be done around 10K times per second.

1 Answers

You don't need to call clear here, as the GC won't treat that as a special signal to garbage collect myMap.

Instead, you should make sure that there's no remaining references to myMap when process finishes executing. Specifically, make sure that doSomethingElse doesn't leak the reference for myMap.

GC will garbage collect myMap once there are no remaining references.

Related