Question

I'm using ScheduledExecutorService.scheduleWithFixedDelay() to schedule periodic launch of thread. It works but threads are accumulating in ThreadStackTrace (with Waiting state). I'm sure that thread which is periodically launched is finished, see example.

Can someone tell me how to launch thread periodically and solve this problem?

class TestThread extends Thread{
    @Override
    public void run(){
        int countThreads =  Thread.getAllStackTraces().keySet().size();
        int running = 0;
        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getState()==Thread.State.RUNNABLE) running++;
            System.out.println(t.getName()+" "+t.getState().toString());
        }        
        System.out.println("TotalThreads:"+countThreads+" Running:"+running+"\n\n");            
    }


}
public class JavaApplication2 {
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

    public static void main(String[] args) {        
        scheduler.scheduleWithFixedDelay(new TestThread(), 0, 10, TimeUnit.SECONDS);
    }    
}

Many thanks

Was it helpful?

Solution

You created a pool of 10 threads. The ExecutorService will create as they are needed and queue the tasks. The threads wait until a task is available (or ready to be executed), one of them gets notified and executes it. The behavior you are seeing seems to indicate that it is implemented in a way that it will create the 10 threads for the first 10 tasks and then re-use them.

I don't know what problem you want to solve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top