How is threadPoolExecutor killed with busy threads?

My question is a bit complicated. Let me try to explain this in full, but if you need more details, feel free to ask me, I will add them.

Recently (through experiments), I found out that if a thread continuously performs work, then something like an integer operation in a while (true) loop, interrupting the thread, does not affect it. The theme continues as nothing happened.

ThreadPoolExecutors are now killed using shutDown () or shutDownNow (). I checked the code for these methods, they use the interrupt () call to kill the stream. So, if all the threads are busy with business, how will the performer be killed? How is it killed, for example, when we use it in spring applications.

One of these artists will look like this:

import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] a) { ExecutorService ex = Executors.newFixedThreadPool(50); for (int i = 0; i < 50; i++) { ex.execute(new Thread() { public void run() { try { File f = File.createTempFile("testfile", "txt"); while (true) { f.canRead(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }); } ex.shutdown(); ex.shutdownNow(); } } 
+6
java multithreading
source share
2 answers

To answer your main question, this would not be the case, unless the JVM was explicitly open to exit through System.exit() .

For long-running operations that should be intermittent, the responsibility for implementing the interrupt flag check lies with Thread.currentThread().isInterrupted() .

For example:

 import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] a) { ExecutorService ex = Executors.newFixedThreadPool(50); for (int i = 0; i < 50; i++) { ex.execute(new Runnable() { public void run() { try { File f = File.createTempFile("testfile", "txt"); while (!Thread.currentThread().isInterrupted()) { f.canRead(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } }); } ex.shutdown(); ex.shutdownNow(); } } 

Also note that creating an instance of Thread not necessary for use only as a Runnable . This creates a kind of indirect attitude that can confuse more naive programmers.

+5
source share

You should not have an input loop in your code.

The thread pool will not wait for threads to exit.

The thread will run forever until the JVM exits

0
source share

All Articles