So I came upon an interesting scenario working on my current project. Given that in Java a running thread cannot be garbage collected even if its reference count is zero. Can an object holding a running thread be garbage collected? Reason I'm interested is that if a thread holding object can be GC'd regardless of the thread status then I could override finalize() to stop the thread. Example code below.
So any ideas if the JVM will even attempt to GC a MyClass object while myThread is running if said MyClass object had a zero reference count.
UPDATE: I think I finally figured it out, see post 13.
http://hardforum.com/showpost.php?p=1033239168&postcount=13
Code:
public class MyClass {
/**
* anon thread implementation as class member.
*/
private Thread myThread = new Thread(){
@Override
public void start(){
this.setDaemon(true);
super.start();
}
@Override
public void run(){
/* Do something until interrupted */
}
@Override
public void interrupt(){
/*
...
Do something to stop the thread
...
*/
//Call super fucntion to set the Interrupted status of the thread.
super.interrupt();
}
};
//C'tor
public MyClass(){
myThread.start();
}
//MyClass methods
public void doSomething(){
//do something to MyClass Object
}
@Override
protected void finalize(){
//Stop the thread before the object gets GC'd
myThread.interrupt();
//Finally let the JVM GC the object.
super.finalize();
}
};
So any ideas if the JVM will even attempt to GC a MyClass object while myThread is running if said MyClass object had a zero reference count.
UPDATE: I think I finally figured it out, see post 13.
http://hardforum.com/showpost.php?p=1033239168&postcount=13