Mohit224
Mohit224

Reputation: 493

How to stop a schedule ScheduledExecutorService

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.

Upvotes: 0

Views: 355

Answers (1)

Gunther Schadow
Gunther Schadow

Reputation: 1739

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.

Upvotes: 0

Related Questions