欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

自定义线程池拒绝策略(创建线程池的三种方法)

程序员文章站 2023-11-24 10:05:04
在java的高并发领域,线程池一直是一个绕不开的话题。有些童鞋一直在使用线程池,但是,对于如何创建线程池仅仅停留在使用executors工具类的方式,那么,创建线程池究竟存在哪几种方式呢?就让我们一起...

在java的高并发领域,线程池一直是一个绕不开的话题。有些童鞋一直在使用线程池,但是,对于如何创建线程池仅仅停留在使用executors工具类的方式,那么,创建线程池究竟存在哪几种方式呢?就让我们一起从创建线程池的源码来深入分析究竟有哪些方式可以创建线程池。

使用executors工具类创建线程池

在创建线程池时,初学者用的最多的就是executors 这个工具类,而使用这个工具类创建线程池时非常简单的,不需要关注太多的线程池细节,只需要传入必要的参数即可。executors 工具类提供了几种创建线程池的方法,如下所示。

  • executors.newcachedthreadpool:创建一个可缓存的线程池,如果线程池的大小超过了需要,可以灵活回收空闲线程,如果没有可回收线程,则新建线程
  • executors.newfixedthreadpool:创建一个定长的线程池,可以控制线程的最大并发数,超出的线程会在队列中等待
  • executors.newscheduledthreadpool:创建一个定长的线程池,支持定时、周期性的任务执行
  • executors.newsinglethreadexecutor:创建一个单线程化的线程池,使用一个唯一的工作线程执行任务,保证所有任务按照指定顺序(先入先出或者优先级)执行
  • executors.newsinglethreadscheduledexecutor:创建一个单线程化的线程池,支持定时、周期性的任务执行
  • executors.newworkstealingpool:创建一个具有并行级别的work-stealing线程池

其中,
executors.newworkstealingpool方法是java 8中新增的创建线程池的方法,它能够为线程池设置并行级别,具有更高的并发度和性能。除了此方法外,其他创建线程池的方法本质上调用的是threadpoolexecutor类的构造方法。

例如,我们可以使用如下代码创建线程池。

executors.newworkstealingpool();
executors.newcachedthreadpool();
executors.newscheduledthreadpool(3);

使用threadpoolexecutor类创建线程池

从代码结构上看threadpoolexecutor类继承自abstractexecutorservice,也就是说,threadpoolexecutor类具有abstractexecutorservice类的全部功能。

既然executors工具类中创建线程池大部分调用的都是threadpoolexecutor类的构造方法,所以,我们也可以直接调用threadpoolexecutor类的构造方法来创建线程池,而不再使用executors工具类。接下来,我们一起看下threadpoolexecutor类的构造方法。

threadpoolexecutor类中的所有构造方法如下所示。

public threadpoolexecutor(int corepoolsize,
			      int maximumpoolsize,
			      long keepalivetime,
			      timeunit unit,
			     blockingqueue<runnable> workqueue) {
	this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
		 executors.defaultthreadfactory(), defaulthandler);
}

public threadpoolexecutor(int corepoolsize,
				int maximumpoolsize,
				long keepalivetime,
				timeunit unit,
				blockingqueue<runnable> workqueue,
			        threadfactory threadfactory) {
this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
	 threadfactory, defaulthandler);
}

public threadpoolexecutor(int corepoolsize,
				int maximumpoolsize,
				long keepalivetime,
			        timeunit unit,
				blockingqueue<runnable> workqueue,
				rejectedexecutionhandler handler) {
this(corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,
	 executors.defaultthreadfactory(), handler);
}

public threadpoolexecutor(int corepoolsize,
				int maximumpoolsize,
				long keepalivetime,
				timeunit unit,
			        blockingqueue<runnable> workqueue,
				threadfactory threadfactory,
				rejectedexecutionhandler handler) {
	if (corepoolsize < 0 ||
		maximumpoolsize <= 0 ||
		maximumpoolsize < corepoolsize ||
		keepalivetime < 0)
		throw new illegalargumentexception();
	if (workqueue == null || threadfactory == null || handler == null)
		throw new nullpointerexception();
	this.acc = system.getsecuritymanager() == null ?
			null :
			accesscontroller.getcontext();
	this.corepoolsize = corepoolsize;
	this.maximumpoolsize = maximumpoolsize;
	this.workqueue = workqueue;
	this.keepalivetime = unit.tonanos(keepalivetime);
	this.threadfactory = threadfactory;
	this.handler = handler;
}

由threadpoolexecutor类的构造方法的源代码可知,创建线程池最终调用的构造方法如下。

public threadpoolexecutor(int corepoolsize, int maximumpoolsize,
			  long keepalivetime, timeunit unit,
			  blockingqueue<runnable> workqueue,
			  threadfactory threadfactory,
		          rejectedexecutionhandler handler) {
	if (corepoolsize < 0 ||
		maximumpoolsize <= 0 ||
		maximumpoolsize < corepoolsize ||
		keepalivetime < 0)
		throw new illegalargumentexception();
	if (workqueue == null || threadfactory == null || handler == null)
		throw new nullpointerexception();
	this.acc = system.getsecuritymanager() == null ?
			null :
			accesscontroller.getcontext();
	this.corepoolsize = corepoolsize;
	this.maximumpoolsize = maximumpoolsize;
	this.workqueue = workqueue;
	this.keepalivetime = unit.tonanos(keepalivetime);
	this.threadfactory = threadfactory;
	this.handler = handler;
}

关于此构造方法中各参数的含义和作用,各位可以移步《高并发之——不得不说的线程池与threadpoolexecutor类浅析》进行查阅。

大家可以自行调用threadpoolexecutor类的构造方法来创建线程池。例如,我们可以使用如下形式创建线程池。

new threadpoolexecutor(0, integer.max_value,
                       60l, timeunit.seconds,
                       new synchronousqueue<runnable>());

使用forkjoinpool类创建线程池

在java8的executors工具类中,新增了如下创建线程池的方式。

public static executorservice newworkstealingpool(int parallelism) {
	return new forkjoinpool
		(parallelism,
		 forkjoinpool.defaultforkjoinworkerthreadfactory,
		 null, true);
}

public static executorservice newworkstealingpool() {
	return new forkjoinpool
		(runtime.getruntime().availableprocessors(),
		 forkjoinpool.defaultforkjoinworkerthreadfactory,
		 null, true);
}

从源代码可以可以,本质上调用的是forkjoinpool类的构造方法类创建线程池,而从代码结构上来看forkjoinpool类继承自abstractexecutorservice抽象类。接下来,我们看下forkjoinpool类的构造方法。

public forkjoinpool() {
	this(math.min(max_cap, runtime.getruntime().availableprocessors()),
		 defaultforkjoinworkerthreadfactory, null, false);
}
 public forkjoinpool(int parallelism) {
	this(parallelism, defaultforkjoinworkerthreadfactory, null, false);
}

public forkjoinpool(int parallelism,
				forkjoinworkerthreadfactory factory,
				uncaughtexceptionhandler handler,
				boolean asyncmode) {
	this(checkparallelism(parallelism),
		 checkfactory(factory),
		 handler,
		 asyncmode ? fifo_queue : lifo_queue,
		 "forkjoinpool-" + nextpoolid() + "-worker-");
	checkpermission();
}

private forkjoinpool(int parallelism,
				 forkjoinworkerthreadfactory factory,
				 uncaughtexceptionhandler handler,
				 int mode,
				 string workernameprefix) {
	this.workernameprefix = workernameprefix;
	this.factory = factory;
	this.ueh = handler;
	this.config = (parallelism & smask) | mode;
	long np = (long)(-parallelism); // offset ctl counts
	this.ctl = ((np << ac_shift) & ac_mask) | ((np << tc_shift) & tc_mask);
}

通过查看源代码得知,forkjoinpool的构造方法,最终调用的是如下私有构造方法。

private forkjoinpool(int parallelism,
				 forkjoinworkerthreadfactory factory,
				 uncaughtexceptionhandler handler,
				 int mode,
				 string workernameprefix) {
	this.workernameprefix = workernameprefix;
	this.factory = factory;
	this.ueh = handler;
	this.config = (parallelism & smask) | mode;
	long np = (long)(-parallelism); // offset ctl counts
	this.ctl = ((np << ac_shift) & ac_mask) | ((np << tc_shift) & tc_mask);
}

其中,各参数的含义如下所示。

  • parallelism:并发级别。
  • factory:创建线程的工厂类对象。
  • handler:当线程池中的线程抛出未捕获的异常时,统一使用uncaughtexceptionhandler对象处理。
  • mode:取值为fifo_queue或者lifo_queue。
  • workernameprefix:执行任务的线程名称的前缀。

当然,私有构造方法虽然是参数最多的一个方法,但是其不会直接对外方法,我们可以使用如下方式创建线程池。

new forkjoinpool();
new forkjoinpool(runtime.getruntime().availableprocessors());
new forkjoinpool(runtime.getruntime().availableprocessors(),
             forkjoinpool.defaultforkjoinworkerthreadfactory,
             null, true);

使用scheduledthreadpoolexecutor类创建线程池

在executors工具类中存在如下方法类创建线程池。

public static scheduledexecutorservice newsinglethreadscheduledexecutor() {
	return new delegatedscheduledexecutorservice
		(new scheduledthreadpoolexecutor(1));
}

public static scheduledexecutorservice newsinglethreadscheduledexecutor(threadfactory threadfactory) {
	return new delegatedscheduledexecutorservice
		(new scheduledthreadpoolexecutor(1, threadfactory));
}

public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize) {
	return new scheduledthreadpoolexecutor(corepoolsize);
}

public static scheduledexecutorservice newscheduledthreadpool(
		int corepoolsize, threadfactory threadfactory) {
	return new scheduledthreadpoolexecutor(corepoolsize, threadfactory);
}

从源码来看,这几个方法本质上调用的都是
scheduledthreadpoolexecutor类的构造方法,scheduledthreadpoolexecutor中存在的构造方法如下所示。

public scheduledthreadpoolexecutor(int corepoolsize) {
	super(corepoolsize, integer.max_value, 0, nanoseconds,
		  new delayedworkqueue());
}

public scheduledthreadpoolexecutor(int corepoolsize, threadfactory threadfactory) {
	super(corepoolsize, integer.max_value, 0, nanoseconds,
		  new delayedworkqueue(), threadfactory);
}

public scheduledthreadpoolexecutor(int corepoolsize, rejectedexecutionhandler handler) {
	super(corepoolsize, integer.max_value, 0, nanoseconds,
		  new delayedworkqueue(), handler);
}

public scheduledthreadpoolexecutor(int corepoolsize,threadfactory threadfactory, rejectedexecutionhandler handler) {
	super(corepoolsize, integer.max_value, 0, nanoseconds,
		  new delayedworkqueue(), threadfactory, handler);
}

而从代码结构上看,
scheduledthreadpoolexecutor类继承自threadpoolexecutor类,本质上还是调用threadpoolexecutor类的构造方法,只不过此时传递的队列为delayedworkqueue。我们可以直接调用scheduledthreadpoolexecutor类的构造方法来创建线程池,例如以如下形式创建线程池。

new scheduledthreadpoolexecutor(3)