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.
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 changethis.configuration
to another value.There's no need. The original HashMap instance will be lost anyway. Initializing configuration doesnt make sense either.
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.