The Java garbage collector (GC) reclaims objects that are not traceable starting from a set of GC roots. That is, if object A is referenced by object B, and object B is referenced by object C, and object C is referenced by a root, then objects A, B, and C are all safe from the garbage collector.
So what are the roots? I don’t know the complete answer, but I do know that the root set includes every local variable and parameter in every running thread.
So, if some local variable or argument in thread 1 still has a reference to the original WorkerClass
instance, then the instance will continue to live.
The original WorkerClass instance will only be reclaimed when it is not referenced by any local or arg in any thread or, by any field in any traceable object. When that happens, it won’t matter to your program any more because your program will no longer have any means to access the object.
P.S., “arguments and locals” includes hidden variables that are part of the Java implementation, and it includes implicit variable such as the this
reference in every object method. Your original WorkerClass
instance can not be reclaimed as long any method call on it (e.g., doLongRunningOperation
) still is active.
solved Java Multithreading : changing variable from multiple threads