Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about java thread lifetime

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!

like image 544
RicardoE Avatar asked Dec 26 '22 23:12

RicardoE


2 Answers

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.

like image 191
JB Nizet Avatar answered Jan 06 '23 21:01

JB Nizet


This thread will never die (unless it crashes or terminates itself).

Does not matter what happens to the thread that started it, or the component that contains it.

If you don't want to hang the JVM, you can declare it a daemon thread. Then it will shut down when everything else does. For more control, you need to make sure you terminate the thread in your own code at the appropriate time.

like image 25
Thilo Avatar answered Jan 06 '23 21:01

Thilo