问题
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.
回答1:
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.
回答2:
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));
}
回答3:
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.
来源:https://stackoverflow.com/questions/17027946/hashmap-and-garbage-collection-do-i-need-to-call-clear-before-variable-re-ass