Please help me find the cause of the thread leak in the code below. TestThreaddoes not receive garbage collection even after run () is completed (verified using the comforting print statement) and the main method exited (verified from the print instruction and profiler).
TestThreadhowever, it receives garbage collection if it is installed as a daemon stream, i.e. t.setDaemon(true). The code below is just an example of code that illustrates the problem in my application. I am trying to use some pre-existing planning class (which was developed by someone else using ScheduledExecutorService). I notice that when I continue to plan a few Runnablewith the class, the created threads will never collect garbage.
public class ThreadTest {
static void runThreadWithExecutor() {
final String name = "TestThread";
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, name);
t.setDaemon(false);
return t;
}
});
ses.schedule(new Runnable() {
@Override
public void run() {
System.out.println("entered " + name);
System.out.println("exiting " + name);
}},
2,
TimeUnit.SECONDS);
}
public static void main(String[] args) throws InterruptedException {
System.out.println("entered main");
runThreadWithExecutor();
Thread.sleep(5000);
System.out.println("exiting main");
}
}