文章目录
1.顺序性验证
2.线程异常恢复机制
3.本质区别
4. FinalizableDelegatedExecutorService 以及DelegatedExecutorService
5.unconfigurableExecutorService与unconfigurableScheduledExecutorService
6 总结
在第一部分中介绍完java中Executors的线程池创建的方式之后,实际上有一个非常好奇的问题。既然newFixedThreadPool(1)也能保证创建只有一个线程运行的线程池,那么为什么还需要一个newSingleThreadExecutor()方法呢?带着这个问题我们来详细分析。
1.顺序性验证
我们通过如下代码对任务的执行顺序进行验证:
public class OrderTest {
public static void main(String[] args) throws Exception{
ExecutorService es1 = Executors.newFixedThreadPool(1);
ExecutorService es2 = Executors.newSingleThreadExecutor();
testOrder(es1);
TimeUnit.SECONDS.sleep(1);
testOrder(es2);
}
private static void testOrder(ExecutorService es) throws InterruptedException{
List<Integer> submit = new ArrayList<>();
List<Integer> result = new ArrayList<>();
IntStream.range(0,100).forEach((i) -> {
submit.add(i);
es.submit(() -> {
result.add(i);
});
});
TimeUnit.SECONDS.sleep(1);
System.out.println(submit);
System.out.println(result);
}
}
执行结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
可以看到,上述代码的执行结果的顺序与提交的顺序都是一致的。两者都是按照提交的先后顺序执行的。因此,网上有人说这两个方法的区别是有序性的显然不能成立。
2.线程异常恢复机制
我们再用如下代码测试出现异常导致线程挂掉的情况:
public static void main(String[] args) throws Exception{
ExecutorService es1 = Executors.newFixedThreadPool(1);
ExecutorService es2 = Executors.newSingleThreadExecutor();
testThreadCrash(es1);
TimeUnit.SECONDS.sleep(1);
testThreadCrash(es2);
}
private static void testThreadCrash(ExecutorService es) {
es.submit(() -> {
throw new IllegalStateException("Error");
});
es.submit(() -> {
System.out.println("running ... ");
});
}
执行结果:
running ...
running ...
两个线程池都能够从异常中恢复。可见这两个方法的异常恢复功能都是一样的。
3.本质区别
那么我们再看看这两个方法的源码:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
与:
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
可以看到,这两个方法返回的对象不一样,一个是ThreadPoolExecutor,而另外一个是FinalizableDelegatedExecutorService。虽然方法定义的是ExecutorService,但是,THreadPoolExecutor是其子类。因此我们可以通过强转来实现,看如下代码:
public static void main(String[] args) {
ExecutorService es1 = Executors.newFixedThreadPool(1);
ExecutorService es2 = Executors.newSingleThreadExecutor();
ThreadPoolExecutor tp1 = (ThreadPoolExecutor) es1;
tp1.setCorePoolSize(2);
System.out.println(tp1.getCorePoolSize());
ThreadPoolExecutor tp2 = (ThreadPoolExecutor) es2;
tp1.setCorePoolSize(2);
System.out.println(tp1.getCorePoolSize());
}
上述代码执行结果:
2
Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.Executors$FinalizableDelegatedExecutorService cannot be cast to java.util.concurrent.ThreadPoolExecutor
at com.dhb.threadpool.DifferentTest.main(DifferentTest.java:17)
也就是说,二者的最大区别在于,newFixedThreadPool(1)的返回结果我们可以通过强转变成ThreadPoolExecutor,但是这个类是可以自行指定线程数的。我们可以通过setCorePoolSize方法来修改。这样也就是说,这两个方法的最大的区别是第一个方法可以修改线程的数量,如果用来指定线程数量为1是不安全的。newSingleThreadExecutor方法则通过提供了一个包装类完全堵住了这个漏洞。
这就是这两个方法的根本区别。
4. FinalizableDelegatedExecutorService 以及DelegatedExecutorService
通过源码我们可以看到,实际上返回的是FinalizableDelegatedExecutorService。
static class FinalizableDelegatedExecutorService
extends DelegatedExecutorService {
FinalizableDelegatedExecutorService(ExecutorService executor) {
super(executor);
}
protected void finalize() {
super.shutdown();
}
}
这个类实际上除了再finalize方法中执行shutdown之外,没有什么内容。其继承了DelegatedExecutorService。
最关键部分还是在DelegatedExecutorService类中。
static class DelegatedExecutorService extends AbstractExecutorService {
private final ExecutorService e;
DelegatedExecutorService(ExecutorService executor) { e = executor; }
public void execute(Runnable command) { e.execute(command); }
public void shutdown() { e.shutdown(); }
public List<Runnable> shutdownNow() { return e.shutdownNow(); }
public boolean isShutdown() { return e.isShutdown(); }
public boolean isTerminated() { return e.isTerminated(); }
public boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException {
return e.awaitTermination(timeout, unit);
}
public Future<?> submit(Runnable task) {
return e.submit(task);
}
public <T> Future<T> submit(Callable<T> task) {
return e.submit(task);
}
public <T> Future<T> submit(Runnable task, T result) {
return e.submit(task, result);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException {
return e.invokeAll(tasks);
}
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException {
return e.invokeAll(tasks, timeout, unit);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException {
return e.invokeAny(tasks);
}
public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return e.invokeAny(tasks, timeout, unit);
}
}
我们可以看到DelegatedExecutorService是AbstractExecutorService的子类,而与ThreadpoolExecutor是兄弟关系。并没有提供修改线程大小的方法。这个类只提供了线程池中一些基本的方法。
但是实际上其构造函数:
DelegatedExecutorService(ExecutorService executor) { e = executor; }
这也就看到了在源码中实际上是new了一个threadPoolExecutor,之后传入后再进行引用。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
这样虽然底层仍然使用的是threadPoolExecutor线程池,但是将部分核心的功能进行了隔离。只提供了抽象类需要的一些方法。
从上面不难看出,这个设计非常巧妙,这也是我们在日后编码的过程中,值得借鉴的地方。
同理,对于newSingleThreadScheduledExecutor和newScheduledThreadPool(1)区别的实现方式也是一样的。
Executors中同样准备了:
DelegatedScheduledExecutorService,这个类也是DelegatedExecutorService的子类。
与之不同的是,
DelegatedScheduledExecutorService还需要实现ScheduledExecutorService接口。
5.unconfigurableExecutorService与unconfigurableScheduledExecutorService
同样,利用上面这部分的原理,Executors还提供了创建线程池之后不可修改配置的方法:
public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
if (executor == null)
throw new NullPointerException();
return new DelegatedExecutorService(executor);
}
与:
public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
if (executor == null)
throw new NullPointerException();
return new DelegatedScheduledExecutorService(executor);
}
这两个方法,可以将创建的线程池的结果,用一个包装类进行包裹,之后这个线程池的配置就不能再修改。
总之,这是我们非常值得借鉴的一个设计方法。
6 总结
本文对Executors的两种方法进行了比较。分析了newFixedThreadPool(1)和newSingleThreadExecutor()的区别。实际上这两种设计是有原因的。而且对于后者这种将核心功能隔隔离的设计模式,非常值得我们借鉴。
————————————————
版权声明:本文为CSDN博主「冬天里的懒猫」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/dhaibo1986/article/details/108586407