Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ExecutorService.shutdownNow method can't stop the thread

Tags:

java

package util.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ShutdownDemo {
 public static void main(String[] args) throws InterruptedException{
  ExecutorService executor = Executors.newSingleThreadExecutor();

  executor.execute(new Runnable(){

   @Override
   public void run() {
    while(true){
     System.out.println("-- test --");
    }
   }

  });

  TimeUnit.SECONDS.sleep(3);

  executor.shutdownNow();
 }
}

I have already invoked the shutdownNow method, why console continue to print "-- test --" ??

like image 773
max shi Avatar asked Dec 15 '10 03:12

max shi


1 Answers

Check out Thread.stop() in JavaDoc for the full reason:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#stop()

Essentially, your thread must stop on it's own in order for your program to stay safe. Just stopping a thread can leave programs in an unpredictable state where locks owned by the thread aren't freed and resources aren't given back to the OS. Eventually leaving your program open to dead locks, memory leaks that can't be freed, and potentially affecting the stability of the OS as well too. This really isn't any different if you were in C or any other language because stopping native threads has these problems. Remember threads aren't processes they share memory and state with other threads so they must behave and cooperate.

Java works on interrupting threads as opposed to killing threads so threads must conform to this model when you write them. Therefore, while(true) in your program is bad practice. Instead you need to see if your thread has been interrupted, and shutdown on it's own. Either with Thread.sleep and handling the InterruptedException properly. Or checking Thread.isInterrupted() in your while loop.

like image 64
chubbsondubs Avatar answered Sep 29 '22 00:09

chubbsondubs