tags:

views:

330

answers:

2

Which is a better way to force GC on ThreadLocal instance?

+3  A: 

Simple answer: you can't force the GC in java. Some may posts tricks but all in all you simply can't.

Well, in fact you can. With exit!

Gilles
+3  A: 

The simple and ugly answer:

System.gc();

This does not guarantee garbage collection of a specific object, but it will tell the VM to make an effort to perform general garbage collection.

Specifically, for a ThreadLocal variable, the contained instance of the variable will not be GC'd until the thread dies or the ThreadLocal instance is no longer accessible. So, you will need to kill the associated thread, or you will need to discard your references to the ThreadLocal variable in order for the System.gc() to have any effect.

However, the very fact that you are calling this points to a larger problem in your code. If you want to get rid of an object, simply having no references to it should be sufficient. The VM will come along some time later and clean up your mess.

To repeat: There is no reason that clean code should be explicitly calling GC.

James Van Huis
Not true. ThreadLocal is implemented as a weak hash map. The garbage collector can't reclaim memory unless you explicitly force it to do so.
As far as I am aware, there is no special "forced" garbage collection contract with a WeakHashMap (or with any object, for that matter). Typically, the garbage collector will reclaim space in a weak hash map whenever the key is no longer in "regular use".
James Van Huis
Just like any other WeakHashMap key, when a Thread is weakly referenceable, the entry is removed. Threads are "root" objects that are considered strongly referenceable while they are alive. I can (and do) stop your attempts at System.gc calls by setting system properties. Don't rely on System.gc.
erickson
erickson: That wouldn't be a performant way to implement ThreadLocal. In fact usually there is some kind of weak hash map in the thread mapping ThreadLocals to values. This can easily leak memory (use google). Who knows what the original poster meant.
Tom Hawtin - tackline
@Tom Hawtin: This leak can be avoided in 1.5+ by using ThreadLocal.remove(key). This will make the ThreadLocal available for GC (barring any other references).
James Van Huis