0

I am using ScheduledExecutorService and initialized it (ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(20);) through a singleton class so that I don't create new threads every time. I then schedule my task using schedule "executorService.schedule(new Runnable(), 20, TimeUnit.SECONDS);

I have 2 questions on this: 1. How do I shutdown a thread once its job is over. If I am trying to call a shutdown method after first execution I get java.util.concurrent.RejectedExecutionException error (as the main executor is shutdown). 2. How do I cancel a long running thread after some time? Let's say if a request is sent and a thread is stuck in the execution how should I cancel it after some time.

Mohit224
  • 443
  • 1
  • 10
  • 24

1 Answers1

0

The best way to end your long running thread is to return from the Runnable#run function. Any attempts to interrupt or cancel may not always work.

Gunther Schadow
  • 1,490
  • 13
  • 22