Reputation: 2196
Relative to this post: use java execute shell command
After the execution of this code
ExecutorTask task = new ExecutorTask();
Thread executorThread = new Thread(task);
executorThread.start();
What happen with task and executorThread objects when "task" finishes its job? Become null? the thread still in memory but stopped? The GC will collect them ?
My actual question is: What happens with the thread object when the runnable object finishes its work?
Upvotes: 0
Views: 588
Reputation: 100050
Threads are objects, subject to GC. However, even if none of your code retains a reference to a thread, it will not be GC'ed until its run method returns. You task is an even more ordinary object; the thread has a reference to it, and if you hold no other reference to it, they will become garbage together.
In response to a comment: don't treat threads any differently than you'd treat anything else. It's always possible to code a memory leak in Java by creation a million billion of something and retaining references to them when you don't want them. On the other hand, much of the time, when we just write code 'naturally', things become garbage in the fullness of time. If you create threads and put them in an array list, it's only a problem if (a) you create an unbounded number of them, and (b) you never let go of the array list. For example, if your program creates a new thread for each, oh, incoming connection, and sticks those into a List, and never removes them, and the list is (essentially) a global variable. One possibly overcomplex mechanism is to wrap the thread in a WeakReference or SoftReference before putting it into the list, but then you're still leaking list space.
Upvotes: 3