Java: Is this enough to delete objects?
I have a HashMap that keeps references to my applications modules.
HashMap<String, Module> modules;
When I do this:
for(String key:modules.keySet()){
modules.remove(key);
}
There should be no more reference to the objects hence they should be removed by the GC at some point. Am I right or did I miss something? Is this secure or is it possible to regain access to the objects somehow?
Is this the same that happens when doing:
modules.clear();
?
In the end a more complicated question: When doing this with GWT, how much can I be sure, that the objects are gone in the browser? I would like to do this on user logout to prevent someone who uses the computer next to retrieve any information from the previous user. Of course most modules do "forget" their data开发者_JS百科 an unDetach(), but I am not sure, all of them do. This information is a plus of course, if someone happens to know I would be thankful =)
The first method could cause problems as you iterate over the keySet and remove elements at the same time. The second methods should do the right thing. And if you have no other references to the modules they should be garbage collected.
For the first few questions relating to garbage collection in Java :
The remove(key)
method of the HashMap is a safe way to remove the object from collection. Doing so will ensure that the object is not referenced by the Collection anymore. However , that itself does not guarentee that the object is not referred to by any other reference also - you as the programmer has to ensure this. If indeed there are no other refs to it , the object will be collected at some point in time. Same is true with clear()
method. Unless you have made any other programming error relating to access to your object references , no one can gain access to these garbage objects.
Note : Use explicit Iterator.remove()
to remove the elements instead of the for
loop. Your current way is prone to ConcurrentModificationException
.
The question rather is who and what else has access to your modules. If there is any chance that some other part of your program might have gotten a reference to one of your modules, you cannot be sure that the GC will remove the module.
In any case, you should not rely on the GC to do anything. It will only run if more space is required and is a system to handle memory cleanup after an application finished executing. If you want to be sure that no sensible information is accessible, remove it explicitly.
Just insert this line in your code:
modules = null;
Then the GC detects, that there is no more reference on that object and cleans it up
精彩评论