Java Multithreading – Do Threads Delete Themselves?

javamultithreadingswing

Let's say I was working on a Swing application. Most of it is run on the EDT using SwingUtilities.invokeLater() inside the main method, because I heard (please correct me if I'm wrong) that that's what you need to do with Swing.

However, some parts of it shouldn't run on the EDT. These parts are parts that take long to complete (I assume that this is because long tasks on the EDT will interfere with GUI stuff the EDT should be doing, and thus these kinds of tasks should be run on parallel, on a different thread. Is this assumption correct?)

To do this, when I need to perform a task that takes long to complete and thus can't be run on the EDT like the rest of the program, I create a new thread and run that task inside it.

My question is: When the run() method of that new thread finishes, aka the thread finished it's job. Does it delete itself? Or does it keep existing in the memory?

Best Answer

When the run() method of that new thread finishes, aka the thread finished it's job. Does it delete itself? Or does it keep existing in the memory?

It mostly deletes itself. The native thread (OS resource) is typically1 destroyed, and the thread stack memory segments (OS resource) are typically deleted. The thread's thread-locals map, the runnable and some other fields of the Thread object are nulled.

There are some additional (user space) thread descriptors managed by the JVM that are used (among other things) by remote agents. I'm not sure when they get destroyed, but evidence suggests that they are typically2 destroyed when thread's run() terminates.

The Thread object will continue to exist as long as it is reachable. So if you want everything to go away when the Thread terminates, don't keep a reference to the Thread or the Runnable.

This is all complicated, and both JVM version and OS specific. If you really need an accurate answer for the version of Java that you are using, check the source code.


1 - In theory, the JVM could recycle the native threads and thread stack segments. However it is standard practice for applications to implement thread recycling at a higher level; e.g. using an ExecutorService, ForkJoinPool or third-party thread pool. For such applications, low level recycling would be redundant and possibly bad for performance.

2 - The evidence is that you don't normally see terminate threads in jstack output. But the flipside is that if a remote agent is watching a thread, that may delay or prevent the thread descriptor from being removed.