About java lifetime

So, I have a "difficult" question, I want to see the opinions of people.

I am programming a component that extends JPanel and does some custom stuff. inside this component I have 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 whether the component is removed from the parent by the remove() method, is this thread still alive, or does it die when the component is removed?

EDIT: Thanks to everyone for your answers, indeed, the thread does not stop removing the starter, so to complete 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(); } } 

first creating a name for my thread using the Thread.setName () method. Thanks!

+4
source share
5 answers

He will still be alive. Running thread is the root for GC. Everything that is accessible from the link chain, starting from the root, is not eligible for GC. This means BTW that your panel will also not be GCed, since the stream contains an implicit reference to the panel ( EnclosingPanel.this ).

You need to stop the thread if you no longer want to start it.

+4
source

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

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

If you do not want to hang the JVM, you can declare it as a daemon thread. Then it will be closed when everything else is done. For more control, you need to make sure that you stop the thread in your own code at the appropriate time.

+3
source

A thread does not die until it finishes its work, or you interrupt .

+1
source

The thread will stop when it exits the run () method, so when the component is removed from the parent by the remove () method, the thread will never end.

+1
source

Take a look at Component.removeNotify. Keep a pointer to the stream in your component:

 public class MyPanel extends JPanel { private Thread thread = ...; public void removeNotify() { super.removeNotify(); thread.interrupt(); } } 

This method is called by awt itself when it decides to remove its own peer-to-peer component (i.e. the Windows or linux component that supports the awt component). According to javadoc:

Makes this component irreproducible, destroying its native screen resource. This method is called by internal tools and should not be called directly by programs. Code overriding this method should call super.removeNotify as the first line of the overriding method.

0
source

All Articles