Home >Java >javaTutorial >Detailed introduction to using ThreadPoolExecutor to execute independent single-threaded tasks in parallel in Java
The task execution framework was introduced in Java SE 5.0, which is a major advancement in simplifying multi-threaded programming development. Use this framework to easily manage tasks: manage the task's lifecycle and execution strategy.
In this article, we use a simple example to show the flexibility and simplicity brought by this framework.
The execution framework introduces the Executor interface to manage the execution of tasks. Executor is an interface used to submit Runnable tasks. This interface isolates task submission from task execution: executors with different execution strategies all implement the same submission interface. Changing the execution strategy will not affect the task submission logic.
If you want to submit a Runnable object for execution, it is very simple:
Executor exec = …; exec.execute(runnable);
As mentioned before, how the executor executes the submitted runnable task is not in As specified in the Executor interface, this depends on the specific type of executor you are using. This framework provides several different executors, and the execution strategies vary for different scenarios.
The most common executor type you may use is the thread pool executor, which is an instance of the ThreadPoolExecutor class (and its subclasses). ThreadPoolExecutor manages a thread pool and a work queue . The thread pool stores the worker threads used to execute tasks.
You must have understood the concept of "pool" in other technologies. One of the biggest benefits of using a "pool" is to reduce the cost of resource creation. After it is used and released, it can be reused. Another indirect benefit is that you can control how much resources are used. For example, you can adjust the size of the thread pool to achieve your desired load without damaging system resources. This framework provides a factory class called Executors to create a thread pool. Using this engineering class you can create thread pools with different characteristics. Although the underlying implementation is often the same (ThreadPoolExecutor), the factory class allows you to quickly set up a thread pool without using complexconstructors. The factory methods of the engineering class are:
Warning: There are some errors and confusion in the understanding that the JVM process will never exit. If you do not close the executorService and just destroy the underlying thread, the JVM will not exit. When the last ordinary thread (non-daemon thread) exits, the JVM will also exit.
Configuring ThreadPoolExecutorIf you decide not to use the Executor factory class, but manually create a ThreadPoolExecutor, you need to use the constructor to create and configure it. Here is one of the most widely used constructors of this class:public ThreadPoolExecutor( int corePoolSize, int maxPoolSize, long keepAlive, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler);As you can see, you can configure the following:
限制执行任务的并发数、限制线程池大小对应用程序以及程序执行结果的可预期性与稳定性有很大的好处。无尽地创建线程,最终会耗尽运行时资源。你的应用程序因此会产生严重的性能问题,甚至导致程序不稳定。
这只解决了部分问题:限制了并发任务数,但并没有限制提交到等待队列的任务数。如果任务提交的速率一直高于任务执行的速率,那么应用程序最终会出现资源短缺的状况。
解决方法是:
为Executor提供一个存放待执行任务的阻塞队列。如果队列填满,以后提交的任务会被“拒绝”。
当任务提交被拒绝时会触发RejectedExecutionHandler,这也是为什么这个类名中引用动词“rejected”。你可以实现自己的拒绝策略,或者使用框架内置的策略。
默认的拒绝策略可以让executor抛出一个RejectedExecutionException异常。然而,还有其他的内建策略:
悄悄地丢弃一个任务
丢弃最旧的任务,重新提交最新的
在调用者的线程中执行被拒绝的任务
什么时候以及为什么我们才会这样配置线程池?让我们看一个例子。
最近,我被叫去解决一个很久以前的任务的问题,我的客户之前就运行过这个任务。大致来说,这个任务包含一个组件,这个组件监听目录树所产生的文件系统事件。每当一个事件被触发,必须处理一个文件。一个专门的单线程执行文件处理。说真的,根据任务的特点,即使我能把它并行化,我也不想那么做。一天的某些时候,事件到达率才很高,文件也没必要实时处理,在第二天之前处理完即可。
当前的实现采用了一些混合且匹配的技术,包括使用UNIX SHELL脚本扫描目录结构,并检测是否发生改变。实现完成后,我们采用了双核的执行环境。同样,事件的到达率相当低:目前为止,事件数以百万计,总共要处理1~2T字节的原始数据。
运行处理程序的主机是12核的机器:很好机会去并行化这些旧的单线程任务。基本上,我们有了食谱的所有原料,我们需要做的仅仅是把程序建立起来并调节。在写代码前,我们必须了解下程序的负载。我列一下我检测到的内容:
有非常多的文件需要被周期性地扫描:每个目录包含1~2百万个文件
扫描算法很快,可以并行化
处理一个文件至少需要1s,甚至上升到2s或3s
处理文件时,性能瓶颈主要是CPU
CPU利用率必须可调,根据一天时间的不同而使用不同的负载配置。
我需要这样一个线程池,它的大小在程序运行的时候通过负载配置来设置。我倾向于根据负载策略创建一个固定大小的线程池。由于线程的性能瓶颈在CPU,它的核心使用率是100%,不会等待其他资源,那么负载策略就很好计算了:用执行环境的CPU核心数乘以一个负载因子(保证计算的结果在峰值时至少有一个核心):
int cpus = Runtime.getRuntime().availableProcessors(); int maxThreads = cpus * scaleFactor; maxThreads = (maxThreads > 0 ? maxThreads : 1);
然后我需要使用阻塞队列创建一个ThreadPoolExecutor,可以限制提交的任务数。为什么?是这样,扫描算法执行很快,很快就产生庞大数量需要处理的文件。数量有多庞大呢?很难预测,因为变动太大了。我不想让executor内部的队列不加选择地填满了要执行的任务实例(这些实例包含了庞大的文件描述符)。我宁愿在队列填满时,拒绝这些文件。
而且,我将使用ThreadPoolExecutor.CallerRunsPolicy作为拒绝策略。为什么?因为当队列已满时,线程池的线程忙于处理文件,我让提交任务的线程去执行它(被拒绝的任务)。这样,扫面会停止,转而去处理一个文件,处理结束后马上又会扫描目录。
下面是创建executor的代码:
ExecutorService executorService = new ThreadPoolExecutor( maxThreads, // core thread pool size maxThreads, // maximum thread pool size 1, // time to wait before resizing pool TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(maxThreads, true), new ThreadPoolExecutor.CallerRunsPolicy());
下面是程序的框架(极其简化版):
// scanning loop: fake scanning while (!dirsToProcess.isEmpty()) { File currentDir = dirsToProcess.pop(); // listing children File[] children = currentDir.listFiles(); // processing children for (final File currentFile : children) { // if it's a directory, defer processing if (currentFile.isDirectory()) { dirsToProcess.add(currentFile); continue; } executorService.submit(new Runnable() { @Override public void run() { try { // if it's a file, process it new ConvertTask(currentFile).perform(); } catch (Exception ex) { // error management logic } } }); } } // ... // wait for all of the executor threads to finish executorService.shutdown(); try { if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { // pool didn't terminate after the first try executorService.shutdownNow(); } if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) { // pool didn't terminate after the second try } } catch (InterruptedException ex) { executorService.shutdownNow(); Thread.currentThread().interrupt(); }
看到了吧,Java并发API非常简单易用,十分灵活,也很强大。真希望我多年前可以多花点功夫写一个这样简单的程序。这样我就可以在几小时内解决由传统单线程组件所引发的扩展性问题。
The above is the detailed content of Detailed introduction to using ThreadPoolExecutor to execute independent single-threaded tasks in parallel in Java. For more information, please follow other related articles on the PHP Chinese website!