我刚刚阅读了这篇文章Runnable
,并认为如果抛出异常并退出,线程池可能会耗尽工作线程。我做了一个小代码并检查了,但池大小没有变化。
public class ThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor tp = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1));
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.execute(new Runnable(){
@Override
public void run() {
System.out.println("Executing & Throwing");
throw new NullPointerException();
}
});
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.execute(new Runnable(){
@Override
public void run() {
System.out.println("Executing & Throwing");
throw new NullPointerException();
}
});
Thread.sleep(1000);
System.out.println(tp.getPoolSize());
tp.shutdown();
}
}
我得到的输出是
0
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at threads.ThreadPoolTest$1.run(ThreadPoolTest.java:18)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Executing & Throwing
1
Exception in thread "pool-1-thread-2" java.lang.NullPointerException
at threads.ThreadPoolTest$2.run(ThreadPoolTest.java:29)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Executing & Throwing
1
这是在 Java 7 上。如文章中所述,是否有任何易受攻击的 java Threadpool 实现?