So I have a "tricky" question, I want to see people opinions.
I’m programming a component, which extends a JPanel and do some custom stuff.
Inside that component I have a Thread, which loops forever like this:
//chat thread
Thread chat_thread = new Thread(new Runnable(){
public void run(){
while(true){
//get chat updates
}
}
});
chat_thread.start();
So the question is, when the component is removed from its parent by the remove() method, is this thread still alive, or does it die when you remove the component?
EDIT:
Thanks all for your replies, indeed the thread does not terminate removing its starter, so in order to terminate this thread from another component, I did the following:
Set<Thread> t = Thread.getAllStackTraces().keySet();
Iterator it = t.iterator();
while(it.hasNext()){
Thread t2 = (Thread)it.next();
if(t2.getName().equals("chat_thread")){
t2.interrupt();
}
}
by first creating a name for my thread with the Thread.setName() method.
Thanks!
It will still be alive. A running thread constitutes a root for the GC. Averything reachable from a chain of references starting from a root is not eligible to GC. This means, BTW, that your panel won’t be GCed either, since the thread holds an implicit reference to the panel (
EnclosingPanel.this).You need to make sure to stop the thread when you don’t want it running anymore.