Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a thread submitted to executer service and interrupt it in Java

I have an executor service, and I want to cancel/interrupt the execution of some of the threads.

For example: Below is my Thread class which prints the thread name after some interval infinitely.

public class MyThread implements Runnable {
String name;

public MyThread(String name) {
    this.name = name;
}

@Override
public void run() {
    try {
        System.out.println("Thread "+ name + " is running");
        sleep(500);
    }catch (InterruptedException e){
        System.out.println("got the interrupted signal");
    }
}
}

Now I'll create multiple threads by giving them name, so that later on I can stop a particular thread with it's name.

As shown below, I am creating 4 threads and want to stop the execution of 2 threads named foo and bar.

public class ThreadTest {

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    MyThread amit = new MyThread("foo");
    MyThread k = new MyThread("bar");
    MyThread blr = new MyThread("tel-aviv");
    MyThread india = new MyThread("israel");
    executorService.submit(foo);
    executorService.submit(bar);
    executorService.submit(tel-aviv);
    executorService.submit(israel);
}
}
like image 509
Amit Avatar asked Jan 05 '23 00:01

Amit


1 Answers

Your MyThreads are not actually being run on threads with those names. They're not being run directly as threads, they are run on the ExecutorService's threads.

So, you need to keep a mapping of name to Future, and then cancel the future when you want to.

Map<String, Future<?>> map = new HashMap<>();
map.put("amit", executorService.submit(amit));
map.put("k", executorService.submit(k));
// ... etc

Then, to cancel amit:

map.get("amit").cancel(true);

Of course, you could simply have kept explicit variables:

Future<?> amitFuture = executorService.submit(amit);
amitFuture.cancel(true);

but this might be unwieldy if you have a lot of variables.

like image 128
Andy Turner Avatar answered Jan 13 '23 13:01

Andy Turner