`
cywhoyi
  • 浏览: 421071 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java Executor Framework

 
阅读更多

Java 5 introduced Thread pool in Java in form of Executor framework, which allows Java programmer to decouple submission of task to execution of task. If you are doing server side programming in Java than Thread pool is an important concept to maintain scalability, robustness and stability of system. For those, who are not familiar with thread pool in Java or concept of thread pool here is one liner, Thread pool in Java is pool of worker threads, which is ready to perform any task given to them, mostly in form of implementation of Runnable or Callable interface. Since Java supports multithreading in programming language itself, it allows multiple thread to run concurrently and perform parallel processing of task. In this article we will learn following things about thread pool in Java :

  1. What is Thread pool in Java?
  2. Why do we need Thread pool in Java ?
  3. What is Executor framework in Java 5?
  4. How to create fixed size thread pool using Executor framework in Java?
  5. Benefits of using Thread Pool in Java?

What is Thread Pool in Java and why we need it

JavaSparrow-med
As I said Thread pool is pool of already created worker thread ready to do the job. Thread pool is one of essential facility any multi-threaded server side Java application requires. One example of using thread pool is creating a web server, which process client request. If you are familiar with socket programming than you know that ServerSocket.accept() is blocking method and blocks until a socket connection made. If only one thread is used to process client request, than it subsequently limit how many client can access server concurrently. In order to support large number of clients, you may decide to use one thread per request paradigm, in which each request is processed by separate Thread, but this require Thread to be created, when request arrived.  Since creation of Thread is time consuming process, it delays request processing. It also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number. Thread pool solves this problem for you, It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread. Since Thread are usually created and pooled when application starts, your server can immediately start request processing, which can further improve server’s response time. Apart from this, there are several other benefits of using Thread pool in Java applications, which we will see in subsequent section. In short, we need thread pools to better mange threads and decoupling task submission from execution. Thread pool and Executor framework introduced in Java 5 is an excellent thread pool provided by library.

Java Thread Pool – Executor Framework in Java 5

Java 5 introduced several useful features like EnumGenericsVariable arguments and several concurrency collections and utilities like ConcurrentHashMap and BlockingQueue etc, It also introduced a full feature built-in Thread Pool framework commonly known asExecutor framework. Core of this thread pool framework is Executor interface which defines abstraction of task execution with method execute(Runnable task) and ExecutorService which extends Executor to add various life-cycle and thread pool management facilities like shutting down thread pool. Executor framework also provides an static utility class called Executors ( similar to Collections ) which provides several static factory method to create various type of Thread Pool implementation in Java e.g. fixed size thread pool, cached thread pool and scheduled thread pool.

Runnable and Callable interface are used to represent task executed by worker thread managed in these Thread pools. Interesting point about Executor framework is that, it is based on Producer consumer design pattern, where application thread produces task and worker thread consumers or execute those task, So it also suffers with limitation of Producer consumer task like if production speed is substantially higher than consumption than you may run OutOfMemory because of queued task, of course only if your queue is unbounded.

How to create fixed size thread pool using Executor framework in Java?

Creating fixed size thread pool using Java 5 Executor framework is pretty easy because of static factory methods provided by Executors class. All you need to do is define your task which you want to execute concurrently and than submit that task to ExecutorService. from them Thread pool will take care of how to execute that task, it can be executed by any free worker thread and if you are interested in result you can query Future object returned by submit()method. Executor framework also provides different kind of Thread Pool e.g. SingleThreadExecutor which creates just one worker thread or CachedThreadPool which creates worker threads as and when necessary. You can also check  Java documentation of Executor Framework for complete details of services provided by this API. Java concurrency in Practice also has couple of chapters dedicated to effective use of Java 5 Executor framework, which is worth reading for any senior Java developer.

Example of Thread Pool in Java

Here is an example of Thread pool in Java, which uses Executor framework of Java 5 to create a fixed thread pool with number of worker thread as 10. It will then create task and submit that to Thread pool for execution:

01 public class ThreadPoolExample {
02  
03     public static void main(String args[]) {
04        ExecutorService service = Executors.newFixedThreadPool(10);
05        for (int i =0; i<100; i++){
06            service.submit(new Task(i));
07        }
08     }
09    
10 }
11  
12 final class Task implements Runnable{
13     private int taskId;
14    
15     public Task(int id){
16         this.taskId = id;
17     }
18    
19     @Override
20     public void run() {
21         System.out.println("Task ID : " this.taskId +" performed by "
22                            + Thread.currentThread().getName());
23     }
24    
25 }
26  
27 Output:
28 Task ID : 0 performed by pool-1-thread-1
29 Task ID : 3 performed by pool-1-thread-4
30 Task ID : 2 performed by pool-1-thread-3
31 Task ID : 1 performed by pool-1-thread-2
32 Task ID : 5 performed by pool-1-thread-6
33 Task ID : 4 performed by pool-1-thread-5

If you look at output of this Java example you will find different threads from thread pool are executing tasks.

Benefits of Thread Pool in Java

Thread Pool offers several benefit to Java application, biggest of them is separating submission of task to execution of task ,which result if more loose coupled and flexible design than tightly coupled create and execute pattern. Here are some more benefits of using Thread pool in Java:

  1. Use of Thread Pool reduces response time by avoiding thread creation during request or task processing.
  2. Use of Thread Pool allows you to change your execution policy as you need. you can go from single thread to multiple thread by just replacing ExecutorService implementation.
  3. Thread Pool in Java application increases stability of system by creating a configured number of threads decided based on system load and available resource.
  4. Thread Pool frees application developer from thread management stuff and allows to focus on business logic.

That’s all on Thread pool in Java 5. we have seen what is thread pool in Java, what is executor framework in java 5, how to create thread pool in Java and some benefits of using thread pool in Java application. no doubt knowledge of thread pool is essential for a server side core Java developer and I suggest reading Java Threads and Concurrency Practice in Java to learn more about concurrency and thread pool.

分享到:
评论

相关推荐

    Java Concurrency Framework 的介绍

    ### Java Concurrency Framework 的介绍 #### 一、概述 本文档由 David Holmes 撰写,旨在为初学者提供一个关于 Java Concurrency Framework 的简单介绍。对于那些希望快速掌握 Java 并发编程基础概念的学习者来说...

    TERASOLUNA Batch Framework for Java Version 3.x 説明資料1

    TERASOLUNA Batch Framework for Java Version 3.x 是NTT DATA Corporation开发的一个批量处理框架,专注于简化Java环境中的批处理开发。这个框架通过组件化的方式提供了必要的功能,使得在线开发者能够快速上手进行...

    Java 9 Concurrency Cookbook - Second Edition

    Separate the thread management from the rest of the application with the Executor framework Solve problems using a parallelized version of the divide and conquer paradigm with the Fork / Join ...

    Java 并发核心编程

    #### 六、Executor Framework Java的`java.util.concurrent.Executor`框架提供了一种灵活的方式来管理和控制线程池中的任务执行: 1. **ThreadPoolExecutor**: 提供了一个可配置的线程池实现。 2. **...

    java入门,面试圣经

    Java集合框架还包括了Java Collections Framework(JCF)、Apache Commons Collections、Google Guava等重要的集合工具库。 在数据结构方面,Java提供了多种用于存储和检索数据的方式,如堆(Heap)、栈(Stack)、...

    java7帮助文档

    The fork/join framework, which is based on the ForkJoinPool class, is an implementation of the Executor interface. It is designed to efficiently run a large number of tasks using a pool of worker ...

    Android-framework详细分析

    Android Framework是基于Java语言构建的,它提供了丰富的API,让开发者能够创建功能丰富的移动应用。其结构主要包括四大组件:Activity、Service、BroadcastReceiver和ContentProvider,这些组件构成了Android应用的...

    JAVA学习文档

    Java提供了Java Media Framework (JMF)来支持多媒体处理,如音频和视频播放。JMF允许开发者创建复杂的媒体应用,支持多种媒体格式。另外,JavaFX也提供了丰富的UI组件和特效,用于创建富客户端应用程序,其中包括...

    Android framework

    这个框架包含了大量Java类库,提供了许多API,使得开发者能够创建功能丰富的Android应用。`framework_intermediates-classes-full-debug.jar` 文件则很可能是Android Framework的编译中间产物,包含了全部的调试模式...

    MyBatis SQL mapper framework for Java.zip

    6. **Executor执行器**: 它是MyBatis内部处理SQL的组件,负责SQL的执行和结果的处理。有SimpleExecutor、ReuseExecutor和BatchExecutor三种类型,分别对应不同的执行策略。 7. **ParameterHandler**: 处理SQL参数,...

    2018年上海高级Java面试题目1

    在Java中,线程池可以使用Executor Framework来实现。 线程工具类 线程工具类是Java中提供的一些工具类,用于辅助线程的开发。常见的线程工具类包括ThreadLocal、Atomic变量、Lock接口等。ThreadLocal可以实现线程...

    java定时器设置及停止的方法

    在Java编程中,定时任务是不可或缺的一部分,它们用于执行周期性操作,如数据备份、监控、清理等。本文将深入探讨如何在Java中设置和停止定时任务,主要关注`java.util.Timer`和`java.util.TimerTask`,以及更现代的...

    JDK19-troubleshooting-guide.pdf

    * 使用 Java 的并发编程模型(如多线程、Executor Framework 等)来提高 JVM 的并发能力。 * 使用 Java 的缓存机制(如 Hibernate 等)来提高应用程序的性能。 2. 应用程序优化技术: * 使用 Java 的性能分析工具...

    java时间触发器配置方法

    Java时间触发器是Java开发中一个非常重要的概念,主要用于实现定时任务和事件调度。在Java中,我们可以使用多种库来创建时间触发器,比如Quartz、Spring Task、ScheduledExecutorService等。下面将详细介绍这些库的...

    Java多线程教程资料(强烈推荐).docx

    优先级调度可以通过 Thread 的 setPriority() 方法来实现,时间片调度可以通过 Thread 的 yield() 方法来实现,线程池调度可以通过 Executor Framework 来实现。 七、Java 多线程新特征 Java 中的多线程新特征包括...

    Absolute Java (5th Edition)

    Java提供了一系列的并发工具,包括线程(Thread)、同步(synchronized)、锁(Lock)和执行器框架(Executor Framework),允许开发者编写高效和可伸缩的并发程序。 知识点13:Java标准版和Java微版 Java有两个...

    java定时执行方法&节拍器

    通常,这样的工具会使定时任务的管理和监控变得更加方便,比如Spring Framework中的`@Scheduled`注解,或者Quartz Scheduler等。 总结一下,Java中实现定时任务主要依靠`java.util.Timer`、`java.util.concurrent....

    定时任务(java)

    Java中的定时任务是程序开发中常见的一种需求,用于在特定时间点或按照预设周期执行某项任务。Java提供了一些内置的工具和框架来支持定时任务的实现,这些工具能够帮助开发者灵活地管理周期性任务,提高代码的可维护...

Global site tag (gtag.js) - Google Analytics