Seraphim's
Seraphim's

Reputation: 12768

HashMap and garbage collection: do I need to call clear() before variable re-assignment?

Maybe it's a silly question but I'm not sure about the garbage collection process.

Consider this code:

private HashMap<String, Parameter> configuration = new HashMap<String, Parameter>();

...
//add some items to configuration
...

//now get another configuration
HashMap<String, Parameter> parameters = new HashMap<String, Parameter>();
for (String parameterName : configurationParameterNameList) {
    parameters.put(parameterName, reader.readParameter(parameterName));
}

//and reassign the variable
this.configuration.clear();
this.configuration = parameters;

Do I need to call configuration.clear() before reassign it? Parameter class contains only a few String variables inside.

Upvotes: 2

Views: 4654

Answers (3)

ola
ola

Reputation: 912

No, garbage collection in java is automatic. This means that if an object does not have a reference to it, it will be gotten rid of. So, like the above answer said, as soon as you take all the references away from the Map, it will become eligible for garbage collection.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

There's no need. The original HashMap instance will be lost anyway. Initializing configuration doesnt make sense either.

private HashMap<String, Parameter> configuration;   
...
configuration = new HashMap<String, Parameter>();
for (String parameterName : configurationParameterNameList) {
    configuration.put(parameterName, reader.readParameter(parameterName));
}

Upvotes: 2

Joachim Sauer
Joachim Sauer

Reputation: 308061

No, you don't need to call clear().

As long as nothing else has a reference to that HashMap it (and all of its entries) will become eligible for garbage collection as soon as you change this.configuration to another value.

Upvotes: 11

Related Questions