Java Thread Pool Example

Source: Internet
Author: User

Use and usage

Network requests usually have two forms : the first, the request is not very frequent, and each connection will remain for a considerable period of time to read data or write data, and finally disconnected, such as file download, network streaming media. Another form is frequent requests, but the connection is disconnected after a small amount of data is read/written. Given the concurrency of the service, if each request comes in after the service starts a thread for it, the resources for the service can be wasteful, especially in the second case. Because it is usually time-consuming to create a thread, set this time to T1, and after the read/write service is T2, when t1>>t2, we should consider a strategy or mechanism to control, so that the service for the second way of request can be done at a lower power consumption.

In general, we can use the thread pool to solve this problem, first of all, when the service starts, we can start several threads and use a container (such as a thread pool) to manage these threads. When the request arrives, you can go from the pool to a thread, perform the task (usually a response to the request), and then put the thread back in the pool when the task ends, and if the request arrives and there are no idle threads in the pool, the request needs to be queued. Finally, the pool is destroyed when the service shuts down.

Structure

The thread pool is typically composed of such a few concepts (interfaces):

    1. thread pool ( thread pool  ) , A pool is a container in which there are many actuators, and each executor is a thread. Of course, the implementation of this container can be linked list, can be an array and so on, do not need to care, need to be concerned that the pool must provide a can be removed from the actuator   method, you may also need a pool of existing active threads, methods to destroy the pool, and so on.

    2. Actuator ( Executor  ) , Each executor is a thread, each executor can execute a task   The task is not clear at this time, it needs to provide the task setter/ Getter method, and as a thread, he can run independently, after the executor executes itself, it needs to put itself into the pool.

    3. tasks ( task  ) , Tasks are specific to each thread, such as downloading a resource, playing a flash fragment, printing a piece of text to the console, and so on, which itself cannot be executed and needs to be handed to the actuator.

The mechanism and structure of the whole pool is this way, of course, a dispatcher (scheduler) is needed to coordinate the main thread and the pool relationship. The purpose of the structure, or interface, is to get us out of the details, to describe the system from a more abstract level, the benefits are simple, and the design framework is more generic and can accommodate many similar situations. Because the task is exactly what we don't know, it can do almost anything in the second case (T1>>T2) that adapts to the network connection summarized above.

Structure diagram of the class

While it is not realistic to design a standard UML view for a simple implementation, it is an encouraging practice, at least to draw a relevant view on the papyrus with a pencil, to help with later maintenance and more advanced extensions.

Simple implementation of thread pool

The implementation can be in multiple languages, we choose the object-oriented Java here, and if you use C, there is no problem, the problem has been described in the previous section, the language is not important.

The pool is a container, and we consider using the Java.util.LinkedList class (possibly because its length is variable and does not need to be considered by our users), that is to say, the pool needs to maintain a linked list.

Public interface Pool {//Pool interface Executor getexecutor (); void destroy ();}

Public interface Executor {//Actuator interface void Settask (Task Task);    Task Gettask (); void StartTask ();}

Since the executor is an object in the pool and there is no external need to know its details, we consider the implementation of the Executor interface as an internal class for the implementation of the pool interface. Another benefit of doing this is that it is easier to manage the pool.

import java.util.linkedlist;import java.util.properties;import redesigned.utils.propreader; public class threadpool implements pool{    private boolean  Isshut;    private linkedlist pool;    private static  properties prop = propreader.getproperties ("Webconfig.properties");     private int size = integer.parseint (Prop.getproperty ("Threadsperpage",  "3"));     public threadpool () {        // read  configuration and set the        // content  of pool by objects of Executor         isshut = false;//set the status of pool to active        &nbsP;pool = new linkedlist ();         for (int i =  0; i < size; i++) {             executor executor = new executorimpl ();//new a executor thread             pool.add (Executor);//add it  to pool             ((ExecutorImpl) executor). Start ();//start it        }    }     public void destroy ()  {//Destroy         Synchronized (pool) {            isshut =  true;//set the status of pool to inactive          &nbsP;  pool.notifyall ();//notify all listener.             pool.clear ();//clear the list of threads         }    }    public Executor  Getexecutor () {        executor ret = null;         synchronized (Pool) {//return if any.             if (Pool.size ()  > 0) {                 ret =  (Executor) Pool.removefirst ();            }else{                 try {           &Nbsp;         pool.wait ();                 } catch  (Interruptedexception e)  {                     e.printstacktrace ();                 }                 ret =  (Executor) Pool.removefirst ();             }        }         return ret;    }    //  Implementation of the executor interface as ThreadPool internal class     private class ExecutorImpl extends  thread implements executor{        private task task;         private object lock = new object ();         //private boolean loop = true;        public  executorimpl () {}        public task gettask ()  {             return this.task;         }        public void  Settask (Task task)  {             this.task = task;        }         public void starttask () {             //system.out.println ("StArt here ");             synchronized (lock) {                 lock.notify ();             }         }        public void run () {             //get a task if any             //then run it             //then put self to pool             while (!isshut) {                 synchronized (Lock) {                     try {                          Lock.wait ();//wait for resource                     } catch  (interruptedexception e)  {                          e.printstacktrace ();                     }                 }                 gettask (). Execute ();//execute the task                  synchronized (pool) {//put it self to the  pool when finish the task                     pool.addfirst (ExecutorImpl.this);                      pool.notifyall ();                 }            }         }    }}

Well, the pool is well designed, and then look at the interface and implementation of the task.

Public interface Task {//This interface is also relatively simple, can be executed, can be taken to execute the result of void execute (); Byte[] GetResult ();}

The implementation of a task can be varied, and the example below is a task that loads resources. How to use it.

Pool pool = new ThreadPool ();//New A Threadpool//load resources on each page, and start #s of thread.for (int i = 0; I < ; Resourcelist.size (); i++) {Executor Executor = Pool.getexecutor ();//Get Executor form pool Task resourceloader = NE    W Resourceloader (String) resourcelist.get (i)); Executor.settask (Resourceloader); Set the task to executor Executor.starttask (); Try to start the executor.} Wait while all task is done, the Destroy the Pool.pool.destroy ();

Advantages or scope of application

    1. In concurrency, a thread that needs to be concurrent does not need to know when it needs to be started, it needs to consider a situation where it takes out an executor from one place and then hands the task to the actuator and waits for the actuator to end, and he cares about what he needs to do, or what he is responsible for. In this way, everyone is simple, because only need to do their own things better. One of the secrets of object-oriented is: Always believe in collaborators, using other people's interfaces instead of implementing all the interfaces themselves.

    2. This kind of t1>>t2 request way is common in the network, it is also common in the actual problem. Therefore, mastering this model may provide convenience and benefit to our future program design.

Summary

synchronization problem: synchronization of threads in the concurrency is very significant, the control of critical resources is the most critical place in the concurrency. For example, in a thread pool, when there are no idle threads in the pool, the new request must wait, and once a task has finished running, it will be placed in the pool on the one hand, and the other threads waiting in pool need to be notified. Each executor thread, starting at the start, enters a wait state, which does not consume CPU resources at this time. When the StartTask () method of the actuator is called externally, the thread is notified to wake up from the wait state, go out of the task, execute it, put the executor itself into the pool, and then continue to wait.

Of course, the implementation of the strategy can be varied, but the nature of the problem has been clearly defined in the second section of the structure .

Recently began to learn Java, but also began to become familiar with the object-oriented thinking mode, this log, as a memo, and secondly can help people who may need. The above can be counted as a summary.

Java Thread Pool Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.