If it doesn't become eligible for garbage collection after returning from run(), should one set its reference to null to do that?
It is always better to explicitly set objects to null (if you are certain that they will not be used in the future) to make the GC's job little easier.
class Test {
protected void finalize() throws Throwable {
System.out.println("test finalized");
};
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
Test test = new Test();
try {
System.out.println(t.getState());
// t.join();
t = null;
test = null;
// System.out.println(t.getState());
Thread.sleep(500); // change this to say 2 or 3 sec i.e, until run() completes. The thread object will be finalized
System.gc();
System.out.println("gc call done..");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyThread extends Thread {
protected void finalize() throws Throwable {
System.out.println("MyThread instance finalized..");
};
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i);
}
}
}
O/P :
case : 1 --> if thread is running when call to gc is made.
RUNNABLE
0
gc call done..
test finalized
1
2
3
4
case :2 --> IF thread has finished running when call to gc is made.
RUNNABLE
0
gc call done..
test finalized
1
2
3
4
MyThread instance finalized..
Being eligible for garbage collection doesn't necessarily mean that the object will be removed from memory. It is at the sole discretion of the underlying operating system / JVM when it is garbage collected. But how can one make sure (either through a Java program or external tool) that the object is completely removed from the memory?
In Java, you can only say when the object becomes unreachable (not GCed, unreachable.). finalize()
will be called when your onjecy becomes unreachable.
If a thread is said to be dead once it finishes its run() method, why can I still be able to execute isAlive() or getState() on the same thread object? Both the calls return false and RUNNABLE respectively. -
The thread might have finished its execution. But it will still be in a state. the terminated state. You are calling these methods on a thread instance. So, it still holds some state data.