简体   繁体   中英

how to make refrences of hashmap/arraylist null in java to release all memory

Does HashMap.clear() or ArrayList.clear() releases memory to shrink the size or the size remains the same?

How arraylist or hashmap references can be made null to be allowed for gc.

If you clear() your Map or Collection , then the garbage collector can collect the objects that were contained in it, as long as they aren't referenced elsewhere. Same with removing all references to the Map or Collection itself (by setting it to null everywhere): As long as the Map , for example, was the only Object "knowing" these references, removing all references to the Map itself will allow the garbage collector to collect the Map and thus also the objects contained in it (as long as they aren't referenced elsewhere, of course).

But just clearing the Map does not guarantee that the garbage collector will actually run - it just CAN clear these objects from memory, IF it runs. But typically you shouldn't worry about that. So you will in all likelyhood not notice a direct and immediate memory gain from calling clear() , but only because the garbage collector does not run all the time.

Calling clear will remove all elements of the collection, if you have no other references to the objects from the collection will make them eligible for garbage collecting.

Assigning null to your collection will do essentially the same as above however it will affect your collection too. If there are no further references to that collection it will become unreachable and eligible for garbage collecting. If you don't keep other references to objects from that collection they can also be garbage collected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM