CompletionService 常用于运行后合并结果。
此类将安排那些完成时提交的任务,把它们结果放置在可使用 take 访问的队列上。该类非常轻便,适合于在执行几组任务时临时使用。
举一个小例子来说明下:
假设不使用等差队列求和公式来计算从1加到500000000的和,分两种方式计算。例子如下
package com.concurrent.program;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CompletionServiceDemo {
private static ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*5);
public static void UseCommonCal(){
long beginTime = System.currentTimeMillis();
long sum = 0L;
for(int i=1;i<=500000000;i++){
sum += i;
}
long endTime = System.currentTimeMillis();
System.out.println("UseCommonCal,从1加到500000000的和是:"+sum);
System.out.println("UseCommonCal,Use time:"+(endTime-beginTime));
}
public static void UseComletionService(){
CompletionService<Long> cs = new ExecutorCompletionService<Long>(pool);
long beginTime = System.currentTimeMillis();
int stmp = 0;
int etmp = 5000000;
int k = 5000000;
for(int i=0;i<100;i++){
final int begin = stmp+1;
final int end = etmp;
cs.submit(new Callable<Long>(){
public Long call() throws Exception {
long result = 0;
for(int j=begin;j<=end;j++){
result += j;
}
return result;
}
});
stmp = etmp;
etmp = etmp + k;
}
long sum = 0L;
try {
for(int i=0;i<100;i++){
Future<Long> future = cs.take();
sum += future.get();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("UseComletionService,从1加到500000000的和是:"+sum);
System.out.println("UseComletionService,Use time:"+(endTime-beginTime));
pool.shutdown();
}
public static void main(String[] args) {
UseCommonCal();
UseComletionService();
}
}
执行结果:
UseCommonCal,从1加到500000000的和是:125000000250000000
UseCommonCal,Use time:1705
UseComletionService,从1加到500000000的和是:125000000250000000
UseComletionService,Use time:662
上面是一个比较俗气的例子,下面来看个实用点的例子:
接下来看一个例子。楼主有一大堆 *.java 文件,需要计算它们的代码总行数。利用 ExecutorCompletionService
可以写出很简单的多线程处理代码:
public int countLines(List<Path> javaFiles) throws Exception {
// 根据处理器数量创建线程池。虽然多线程并不保证能够提升性能,但适量地
// 开线程一般可以从系统骗取更多资源。
ExecutorService es = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() * 2);
// 使用 ExecutorCompletionService 内建的阻塞队列。
CompletionService cs = new ExecutorCompletionService(es);
// 按文件向 CompletionService 提交任务。
for (final Path javaFile : javaFiles) {
cs.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// 略去计算单个文件行数的代码。
return countLines(javaFile);
}
});
}
try {
int loc = 0;
int size = javaFiles.size();
for (int i = 0; i < size; i++) {
// take 方法等待下一个结果并返回 Future 对象。不直接返回计算结果是为
// 捕获计算时可能抛出的异常。
// poll 不等待,有结果就返回一个 Future 对象,否则返回 null。
loc += cs.take().get();
}
return loc;
} finally {
// 关闭线程池。也可以将线程池提升为字段以便重用。
// 如果任务线程(Callable#call)能响应中断,用 shutdownNow 更好。
es.shutdown();
}
}
CompletionService
接口的实例可以充当生产者和消费者的中间处理引擎,从而达到将提交任务和处理结果的代码进行解耦的目的。生产者调用submit
方法提交任务,而消费者调用 poll
(非阻塞)或 take
(阻塞)方法获取下一个结果:这一特征看起来和阻塞队列(BlockingQueue
)类似,两者的区别在于 CompletionService
要负责任务的处理,而阻塞队列则不会。
在 JDK 中,该接口只有一个实现类 ExecutorCompletionService
,该类使用创建时提供的 Executor
对象(通常是线程池)来执行任务,然后将结果放入一个阻塞队列中。
如果不是精确计算型的线程,对线程执行结果要求不高,而对效率和响应性要求的线程,在获取返回结果时,可以使用Future的带参数的get方法:
get(long timeout, TimeUnit unit)
如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。