Which is a better way to force GC on ThreadLocal instance?
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!
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.