Rohit Narang
Rohit Narang

Reputation: 55

What is the elegant way to Stop a running thread from executor service

enter image description here Threads are not stopped even after calling Interruption from Executors shutdownNow method.
Thread Call functionality is running in a while loop , which is checking for Interruption flag. I tried sending Interruption flag to the running thread after a certain period, but it is still executing.I want to force stop the thread. Can anybody tell this behavior. Attaching the sample Java code:

public class TestExecutor {


static volatile int j = 1; 

public static void main(String[] args) {

    ExecutorService pool = Executors.newFixedThreadPool(5);
    for (int i = 1; i <= 10; ++i) {

        Future<Map<String, List<String>>> abc =   pool.submit(new Callable<Map<String, List<String>>>() {
        volatile boolean abortFlag = false;
        @Override
        public Map<String, List<String>> call() throws Exception {


            while(!abortFlag){
                long start = System.currentTimeMillis();
                for(int k=0; k < 10e4 ;k++){
                    abortFlag = abort();
                    System.out.println(Thread.currentThread().getName() +" " +abortFlag);
                }
                System.out.println("counter val is:" +Thread.currentThread().getName()  +" : "  +j++);
                long end = System.currentTimeMillis();
                System.out.println("time for one execution : "  +" "  +Thread.currentThread().getName()  +" :" +(end-start));
                return null;
            }

            return null;
        }
        private boolean abort() {

            if(Thread.currentThread().isInterrupted()){
                return true;
            }else{
                return false;
            }

        }
    });
    }
    pool.shutdown();

    try {
        if (pool.awaitTermination(3000, TimeUnit.MILLISECONDS)) {
            System.out.println("task completed");
        } else {
            System.out.println("Forcing shutdown...");
            pool.shutdownNow();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }


System.out.println("Closed");


}

} `

Upvotes: 0

Views: 2840

Answers (2)

Roshan
Roshan

Reputation: 667

shutDown() , will wait for all the active/queued tasks to complete and will not allow any new task to be submitted.

shutDownNow() , will not allow any new task and tasks still in the queue will not be run and currently running tasks/threads will be interrupted.

So, The reason why the threads where still running even after shutdownNow is called is because threads still in the for loop will still be running since no action is taken on the abortFlag. in the for loop.

Change Code Snippet :

 abortFlag = abort();
 if(abortFlag){
   System.out.println(Thread.currentThread().getName()+" K="+k);
   break;
 }

Thanks Roshan

Upvotes: 1

diginoise
diginoise

Reputation: 7630

You have a 'long' execution before you act on abortFlag in while(!abortFlag). As per the loop below, you will have up to 10k print outs before you have opportunity to exit. If your application can exit before finishing that 'long' task, then just exit the inner loop when the flag has been toggled:

for(int k=0; k < 10e4 ;k++){
    abortFlag = abort();
    if (abortFlag) { 
        break;
    }
    System.out.println(Thread.currentThread().getName() +" " +abortFlag);
}

Upvotes: 1

Related Questions