简体   繁体   中英

What exactly happens when a thread crashes?

I am a little confused on what happens when there is an uncaught exception. For example:

public class TestActivity extends Activity {
  private Fish fish;

  void onCreate(Bundle savedInstanceState) {
    new Thread(new Runnable() {
        fish.swim();
    }).start();
  }
}

The code above crashes the app when executed even if its on a different thread since fish was never initialized and a NPE happens. However:

public class TestActivity extends Activity {
  private Fish fish;

  void onCreate(Bundle savedInstanceState) {
    ScheduledExecutorService executorService =     
  Executors.newScheduledThreadPool(10);
            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    fish.swim();

                }
            }, 0, TimeUnit.SECONDS);
  }
}

The code above doesn't crash the app even though it produces a NullPointerException, is it because it is in a different thread pool? Does that mean if I have a threadpool with 10 different threads running, does the whole threadpool crash and the 9 other threads will die?

I am a bit confused because I previously thought that when a thread crashes, only that thread dies and the threadpool it was living in is unaffected. Can someone explain this to me please?

From the of docs ThreadPoolExecutor :

Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.

The reason why the code does not crash your app is because the exception is silently handled for you. Also, when the submitted task encounters an exception, its further executions are silently suppressed.

In case of a scheduled thread pool, the value that you pass determines the number of threads that can be scheduled concurrently. So, you will have just 1 thread in the pool. This is in contrast with the fixed thread pool which will maintain the said number of threads in the pool even if a few of them crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM