q126y q126y - 1 year ago 113
Java Question

Java Multithreading : changing variable from multiple threads

Say I have class

public class OuterClass
public static WorkerClass worker;

In thread 1

The following command is executed


while the
is executed, in thread 2

Outerclass.worker = new WokerClass();

What will happen to the
in thread 1?

Will the
Object referenced by thread 1 be garbage collected, only after the
is complete or can it be abruptly terminated to garbage collect

Edit :

I think it should be GC'ed, since it is no longer referenced. But what will happen to the
? will it be terminated abruptly?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download