code-gijoe
code-gijoe

Reputation: 7244

What is the proper way to dispose of a complex data structure?

I have a rather complex data structure that is stacks Map structures inside other maps:

Map<String, Map<Integer, PerformanceScopeMeta> > complex;

Here is the PerformanceScopeMeta class:

class PerformanceScopeMeta {
    /* Meta information */
    private Map<String, String> meta;
    private List<PerformanceMessage> messages;
 }

This is what I do to "make the memory available for garbage collection" :

complex.put("SOME_KEY", null);

Is that enough or am I completely wrong?

Upvotes: 0

Views: 131

Answers (3)

NPE
NPE

Reputation: 500713

To remove a key from the map, use complex.remove("SOME_KEY"). This will make the corresponding value eligible for garbage collection, provided there are no remaining live references to it.

Upvotes: 4

BlackJoker
BlackJoker

Reputation: 3191

use complex.remove("SOME_KEY") is OK if the removed value or any objects in that removed map are not referenced by any of your code.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502406

Well if nothing else has a reference to the map, then yes, that's enough (assuming your map accepts null values).

But bear in mind that if the object that complex refers to becomes eligible for garbage collection, then you don't need to do anything at all. It's only if you need to clear part of the map that you need to do this. It's relatively rare that you have to do anything for the sake of the garbage collector, in my experience.

Personally I'd use Map.remove instead of your suggested code though:

complex.remove("SOME_KEY");

You don't really want an entry with a null value, I assume... you just want to get rid of the entry altogether, right?

Upvotes: 7

Related Questions