线程池中的所有任务执行完毕后,线程并没有停止,导致JVM出现OOM问题。后来查找了下面链接的资料,解决问题。
问题及现象:
public static void main(String[] args) {
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 10, TimeUnit.SECONDS, queue);
for (int i = 0; i < 20; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(this.hashCode() / 1000);
for (int j = 0; j < 10; j++) {
System.out.println(this.hashCode() + ":" + j);
Thread.sleep(this.hashCode() % 2);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("thread %d finished", this.hashCode()));
}
});
}
}
image.png
任务已经执行完毕了,但是线程池中的线程并没有被回收,程序任然处于运行状态。但是在ThreadPoolExecutor的参数里面设置了超时时间的,好像没起作用,原因如下:
工作线程回收需要满足三个条件:
参数allowCoreThreadTimeOut为true
该线程在keepAliveTime时间内获取不到任务,即空闲这么长时间
当前线程池大小 > 核心线程池大小corePoolSize。
解决一:allowCoreThreadTimeOut设置为true
public static void method1() {
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.SECONDS, queue);
executor.allowCoreThreadTimeOut(true);
for ( int i = 0; i < 20; i++) {
executor.execute( new Runnable() {
public void run() {
try {
System. out.println( this.hashCode()/1000);
for ( int j = 0; j < 10; j++) {
System. out.println( this.hashCode() + ":" + j);
Thread. sleep(this.hashCode()%2);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System. out.println(String. format("thread %d finished", this.hashCode()));
}
});
}
}
需要注意的是,allowCoreThreadTimeOut 的设置需要在任务执行之前,一般在new一个线程池后设置;在allowCoreThreadTimeOut设置为true时,ThreadPoolExecutor的keepAliveTime参数必须大于0。
解决二:调用shutdown方法
public static void method1() {
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.SECONDS, queue);
for ( int i = 0; i < 20; i++) {
executor.execute( new Runnable() {
public void run() {
try {
System. out.println( this.hashCode()/1000);
for ( int j = 0; j < 10; j++) {
System. out.println( this.hashCode() + ":" + j);
Thread. sleep(this.hashCode()%2);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System. out.println(String. format("thread %d finished", this.hashCode()));
}
});
}
executor.shutdown();
}
在任务执行完后,调用shutdown方法,将线程池中的空闲线程回收。该方法会使得keepAliveTime参数失效。