Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt ExecutorService's threads

When using the ExecutorService returned by Executors.newSingleThreadExecutor(), how do I interrupt it?

like image 1000
Ofek Ron Avatar asked Feb 14 '12 16:02

Ofek Ron


People also ask

How do I interrupt a thread?

A thread can send an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. This means interruption of a thread is caused by any other thread calling the interrupt() method. void interrupt() - Interrupts the thread.

Can you interrupt a sleeping thread?

interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

How do I stop an executor's thread?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing.

What does thread currentThread () interrupt () do?

By calling Thread. currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.


1 Answers

In order to do this, you need to submit() a task to an ExecutorService, rather than calling execute(). When you do this, a Future is returned that can be used to manipulate the scheduled task. In particular, you can call cancel(true) on the associated Future to interrupt a task that is currently executing (or skip execution altogether if the task hasn't started running yet).

By the way, the object returned by Executors.newSingleThreadExecutor() is actually an ExecutorService.

like image 170
erickson Avatar answered Sep 27 '22 16:09

erickson