多线程java.util.concurrent.RejectedExecutionException

项目运行一段时间后现场突然报了一个异常,多线程读取本地文件时失败导致文件大量积压,查看日志发现以下异常:
java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@12bb4df8 rejected from java.util.concurrent.ThreadPoolExecutor@4cc77c2e[Shutting down, pool size = 5, active threads = 0, queued tasks = 0, completed tasks = 50]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
由于本地测试只放了一两个文件所以忽略了此问题,放多个文件的时候该问题重现。
从异常名称里很容易分析出是提交的任务被线程池拒绝了。查看源码发现是在Activity里,AsyncTask是在自定义的线程池的运行的,但是onDestory函数里却是先显示调用了线程池的shutdown方法,然后才是AsyncTask的cancel操作,因此可能导致任务被拒绝。
ThreadPoolExecutor
一个ExecutorService,它使用可能的几个线程池之一执行每个提交的任务,通常使用Executors工厂方法配置,但是查看源码,发现工厂方法也是统一调用了ThreadPoolExecutor类,以为例,源码如下:
public class Executors {
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(),
                                  threadFactory);
}

}
虽然我一直认同程序员应使用较为方便的Executors工厂方法Executors.newCachedThreadPool() (无界线程池,可以进行自动线程回收)、Executors.newFixedThreadPool(int)(固定大小线程池)和Executors.newSingleThreadExecutor()(单个后台线程),但是通过源码我们可以发现最后他们均调用了ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) 方法,因此我们在分析java.util.concurrent.RejectedExecutionException之前,需要深入学习一下ThreadPoolExecutor的使用。
核心池和最大池的大小
TreadPoolExecutor将根据corePoolSize和maximumPoolSize设置的边界自动调整池大小。当新任务在方法execute(java.lang.Runnable)中提交时,如果运行的线程少于corePoolSize,则创建新线程来处理请求,即使其他辅助线程是空闲的。如果运行的线程多于corePoolSize而少于maximumPoolSize,则仅当队列满时才创建新的线程。如果设置的corePoolSize和maximumPoolSize相同,则创建了固定大小的线程池。如果将maximumPoolSize设置为基本的无界值(如Integer.MAX_VALUE),则允许线程池适应任意数量的并发任务。
保持活动时间
如果池中当前有多于corePoolSize的线程,则这些多出的线程在空闲时间超过keepAliveTime时将会终止。
排队
所有BlockingQueue都可用于传输和保持提交的任务。可以使用此队列与池大小进行交互:
如果运行的线程少于corePoolSize,则Executor始终首选添加新的线程,而不进行排队。
如果运行的线程等于或多于corePoolSize,则Executor始终首选将请求加入队列,而不添加新的线程。
如果无法将请求加入队列,则创建新的线程,除非创建此线程超出maximumPoolSize,在这种情况下,任务将被拒绝(抛出RejectedExecutionException)。
排队有三种通用策略:
直接提交。工作队列的默认选项是synchronousQueue,它将任务直接提交给线程而不保持它们。在此,如果不存在可用于立即运行任务的线程,则试图把任务加入队列将失败,因此会构造一个新的线程。此策略可以避免在处理可能具有内部依赖性的请求集时出现锁。直接提交通常要求无界maximumPoolSizes以避免拒绝新提交的任务。当命令以超过队列所能处理的平均数连续到达时,此策略允许无界线程具有增加的可能性。
无界队列。使用无界队列(例如,不具有预定义容量的LinkedBlockingQueue)将导致在所有corePoolSize线程都忙时新任务在队列中等待。这样,创建的线程就不会超过corePoolSize(因此,maximumPoolSize的值也就无效了)。
有界队列。当使用有限的maximumPoolSizes时,有界队列(如ArrayBlockingQueue)有助于防止资源耗尽,但是可能较难调整和控制。队列大小和最大池大小可能需要相互折衷:使用大型队列和小型池可以最大限度的降低CPU使用率、操作系统资源和上下文切换开销,但是可能导致人工降低吞吐量。如果任务频繁阻塞,则系统可能为超过您许可的更多线程安排时间,使用小型队列通常要求较大的池大小,CPU使用率较高,但是可能遇到不可接受的调度开销,这样可会降低吞吐量。
终止
程序不再引用的池没有剩余线程会自动shutdown。如果希望确保回收取消引用的池(即使用户忘记调用shutdown()),则必须安排未使用的线程最终终止。
分析
通过对ThreadPoolExecutor类分析,引发java.util.concurrent.RejectedExecutionException主要有两种原因:

  1. 线程池显示的调用了shutdown()之后,再向线程池提交任务的时候,如果你配置的拒绝策略是ThreadPoolExecutor.AbortPolicy的话,这个异常就被会抛出来。
  2. 当你的排队策略为有界队列,并且配置的拒绝策略是ThreadPoolExecutor.AbortPolicy,当线程池的线程数量已经达到了maximumPoolSize的时候,你再向它提交任务,就会抛出ThreadPoolExecutor.AbortPolicy异常。

显示关闭掉线程池
这一点很好理解。比如说,你向一个仓库去存放货物,一开始,仓库管理员把门给你打开了,你放了第一件商品到仓库里,但是当你放好出去后,有人把仓库门关了,那你下次再来存放物品时,你就会被拒绝。示例代码如下:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TextExecutor {
public ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);
public ExecutorService cachedExecutorService = Executors.newCachedThreadPool();
public ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();

public void testExecutorException() {
	for (int i = 0; i < 10; i ++) {
		fixedExecutorService.execute(new SayHelloRunnable());
		fixedExecutorService.shutdown();
	}
}

private class SayHelloRunnable implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			System.out.println("hello world!");
		}
		
	}
}

public static void main(String[] args) {
	TextExecutor testExecutor = new TextExecutor();
	testExecutor.testExecutorException();
}

}
解决方案

  1. 不要显示的调用shutdown方法,例如Android里,只有你在Destory方法里cancel掉AsyncTask,则线程池里没有活跃线程会自己回收自己。
  2. 调用线程池时,判断是否已经shutdown,通过API方法isShutDown方法判断,示例代码:
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

public class TextExecutor {
public ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);
public ExecutorService cachedExecutorService = Executors.newCachedThreadPool();
public ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();

public void testExecutorException() {
	for (int i = 0; i < 10; i ++) {
		// 增加isShutdown()判断
		if (!fixedExecutorService.isShutdown()) {
			fixedExecutorService.execute(new SayHelloRunnable());
		}
		fixedExecutorService.shutdown();
	}
}

private class SayHelloRunnable implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			System.out.println("hello world!");
		}
		
	}
}

public static void main(String[] args) {
	TextExecutor testExecutor = new TextExecutor();
	testExecutor.testExecutorException();
}

}
线程数量超过maximumPoolSize
示例代码里使用了自定义的ExecutorService,可以复现这种问题:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TextExecutor {
public ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);
public ExecutorService cachedExecutorService = Executors.newCachedThreadPool();
public ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, 5, 0, TimeUnit.MILLISECONDS, new SynchronousQueue());

public void testExecutorException() {
	for (int i = 0; i < 10; i ++) {
		// 增加isShutdown()判断
		if (!fixedExecutorService.isShutdown()) {
			fixedExecutorService.execute(new SayHelloRunnable());
		}
		fixedExecutorService.shutdown();
	}
}

public void testCustomerExecutorException() {
	for (int i = 0; i < 100; i ++) {
		customerExecutorService.execute(new SayHelloRunnable());
	}
}

private class SayHelloRunnable implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			System.out.println("hello world!");
		}
		
	}
}

public static void main(String[] args) {
	TextExecutor testExecutor = new TextExecutor();
	testExecutor.testCustomerExecutorException();;
}

}
解决方案

  1. 尽量调大maximumPoolSize,例如设置为Integer.MAX_VALUE
    public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS, new SynchronousQueue());
  2. 使用其他排队策略,例如LinkedBlockingQueue
    public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, 5, 0, TimeUnit.MILL
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值