I was thinking to improve my threading fundamentals, so I
planned to make few notes for myself that will assist me in future (Obviously
at the time of Interviews). Following questions and answers have been taken
from stackoverflow.com. This post is a sticky notes post for me.
I just loved this
question. Java
Thread Garbage collected or not
import java.util.Calendar;
public class RunningThreadProblem {
public static void
main(String[] args) {
Thread cur = new
Thread(new ImplementedThread());
cur.start();//Line
1
cur = null;//Line
2
}
}
class ImplementedThread implements
Runnable{
@Override
public void run()
{
while(true){
try
{
System.out.println("Time -> " +
Calendar.getInstance().getTimeInMillis());
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Result for this code is as follows
Time ->
1373472403175
Time ->
1373472404176
Time -> 1373472405176
Time ->
1373472406176
Time ->
1373472407176
Time ->
1373472408176
Time ->
1373472409177
Time ->
1373472410177
Time ->
1373472411177
Time ->
1373472412177
Even after this, I had to terminate the process. GC has not
collected the thread even if I had assigned it to null. I assigned the thread object (Line 2)
to NULL as soon as I started the thread (Line 1). So based on general garbage
collection concepts, it should have been garbage collection. So why did this
thread not garbage collected?
Answer
Running threads are, by definition, immune to GC. The GC
begins its work by scanning "roots", which are deemed always
reachable; roots include global variables ("static fields" in
Java-talk) and the stacks of all running threads (it can be imagined that the
stack of a running thread references the corresponding Thread instance).
When the garbage
collector determines whether your object is 'reachable'
or not, it is always doing so using the set of garbage collector roots as
reference points.
No comments:
Post a Comment