Reputation: 4556
In Java, at some point in code I want to free memory taken by a huge HashMap<Integer, ArrayList<Integer>>
object. Is it enough to point it to null
like below:
Map<Integer, ArrayList<Integer>> complexObject = new HashMap<Integer, ArrayList<Integer>>(1000000);
...
complexObject = null;
?
Upvotes: 2
Views: 228
Reputation: 20132
I just read this article, there is something about freeing memory in it, too. Check it out, nulling does not always help you.
Upvotes: 0
Reputation: 2768
There is no guarantee of freeing memory. GC will run and pickup nulls so that's all you can do yes.
Upvotes: 0
Reputation: 178313
You cannot explicitly de-allocate Java objects. But you can do the following:
null
.System.gc()
to "suggest" to the JVM to run the garbage collector, which deallocates no-longer used objects, although it's not guaranteed that calling this method will actually run the garbage collector.Upvotes: 2
Reputation: 9011
Setting its reference to null will mark it available to the garbage collector next time it decides to run if there are indeed no more references to said object laying around anywhere. When the GC decides to run however, is not set in stone.
This is a big point where Java is different from C, but don't worry. 99.9% of the time you can trust the GC has your back.
Upvotes: 1