Sophie Sperner
Sophie Sperner

Reputation: 4556

Delete complex objects at runtime in Java

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

Answers (4)

Simulant
Simulant

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

awm
awm

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

rgettman
rgettman

Reputation: 178313

You cannot explicitly de-allocate Java objects. But you can do the following:

  1. Remove all references to the item you no longer need. You can do this by setting your only reference to an object to null.
  2. Call 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

thatidiotguy
thatidiotguy

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

Related Questions