Java: Thread Pool Basics

Source: Internet
Author: User

Basic Understanding

The following excerpt from Baidu Encyclopedia
Thread pool concept: The thread pool is a form of multithreading that adds tasks to the queue during processing, and then starts these tasks automatically after the thread is created.
The role of the thread pool: in object-oriented programming, it takes time to create and destroy objects because an object is created to acquire memory resources or other resources. More so in Java, virtual machines will attempt to track each object so that it can be garbage collected after the object is destroyed. So one way to improve the efficiency of the service process is to minimize the number of objects created and destroyed, especially the resource-intensive object creation and destruction. How to use the existing object to serve is a key problem that needs to be solved, in fact, this is the reason that some "pooling resources" technology produces. For example, you are familiar with the database connection pool is to follow this idea produced.

In short: The thread pool is the system through the concept of pooling resources, to achieve a means of saving resources.
About Threads and tasks: Java becomes the fourth edition of Thought, which is clearly described in one word: threads are used to drive tasks. The first class thinks that a thread is a task, but it is not.

java thread pool

Java has four common thread pools, which are returned as static factories in the Java.util.concurrernt.Executors class:

    • Newcachedthreadpool : Creates a thread pool that creates a new thread as needed, but reuses the when a previously constructed thread is available them. (Creates a thread pool that creates new threads as needed, but would reuse previously constructed threads when they is AVA Ilable.)
    • Newfixedthreadpool : Creates a thread pool that can reuse fixed threads to run these threads in a shared, unbounded queue. (Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.)
    • Newscheduledthreadpool : Creates a thread pool that can schedule a Run command after a given delay, or periodically to execute. (Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.)
    • Newsinglethreadexecutor : Creates a thread pool that uses a single thread and runs it in a unbounded queue. (Creates an Executor, uses a single worker, thread operating off an unbounded queue.)

Observe these static factories, for Newcachedthreadpool, NEWSINGLETHREADEXECUTOR,API clients directly call, and for Newfixedthreadpool, the client needs to focus on parameters: int Nthreads;newscheduledthreadpool, the client needs to focus on parameters: int corepoolsize.

So let's see what these parameters mean in the source code.

To create a cachedthreadpool, for example:

ExecutorService ctp = Executors.newCachedThreadPool();

newCachedThreadPool()The source code of the method is as follows:

publicstaticnewCachedThreadPool() {        returnnew ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue<Runnable>());    }

We come straight to the Threadpoolexecutor class and see what the parameters of the constructors mean.

    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue,                              ThreadFactory threadFactory,                              RejectedExecutionHandler handler) {        ...    }

Because for the time being only for the basics of getting started, so the next few parameters we don't care about, let's think they are the thread pool underlying operations related parameters, we only look at the previous four or even only look at the previous two API client will use the parameters.
Source files:

    • Corepoolsize: Number of threads in the resident thread pool
    • Maximunpoolsize: Maximum number of threads allowed in a thread pool
    • KeepAliveTime: When the number of existing threads exceeds the number of resident, the idle line Chengjo is terminated when the maximum length of time has not yet been awaited for a new task.
    • Unit:keepalivetimed Unit of Time

Let's take a look at some of the previous parameters when creating several thread pools what the default is:
1, Cached thread pool: You can see that the number of resident is 0, the maximum number of threads can be very large, when the thread is idle for 60 seconds no new task is terminated. This effect can be seen from the name.

    publicstaticnewCachedThreadPool() {        returnnew ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue<Runnable>());    }

2. Fixed thread pool: you can see that the number of resident is determined by the client, the maximum number of threads is also, when the thread is idle, it is terminated immediately.

    publicstaticnewFixedThreadPool(int nThreads) {        returnnew ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>());    }

3. Single thread pool: Only one worker thread is allowed, and no task is terminated.

    publicstaticnewSingleThreadExecutor() {        returnnew FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(11,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue<Runnable>()));    }

4. Scheduled thread pool: The number of resident threads is determined by the client

    publicScheduledThreadPoolExecutor(int corePoolSize) {        super0, NANOSECONDS,              new DelayedWorkQueue());    }
Simple Example
 Public  class Test {    Private StaticExecutorservice cached = Executors.newcachedthreadpool ();Private StaticExecutorservice fixed = Executors.newfixedthreadpool (3);Private StaticFileWriter FW;Static{Try{FW =NewFileWriter ("J:/log.txt"); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    } Public Static void Main(string[] args) {//TODO auto-generated method stubRunnable sellingapple =NewSelling ("Apple"); Runnable Sellingbanana =NewSelling ("Banana"); for(inti =0; I <5;        i++) {Cached.execute (sellingapple);    } cached.execute (Sellingbanana); }Private Static  class selling implements Runnable {        Private intCount = -;PrivateString item; Public Selling(String Item) { This. item = Item; } Public void Run() {//TODO auto-generated method stub             while(true) {synchronized( This) {if(Count <1) { Break;                } sell (); }Try{Thread.Sleep (1); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace ();        }} cached.shutdown (); }Private void Sell() {Try{Fw.write (Thread.CurrentThread (). GetName () +"SOLD"+ Item +": #"+ count--+"\ n"); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }    }}

Result: We have a total of 6 threads open in the cache thread pool, the first 5 is used to drive the sale of apples this task, the last 6th to sell bananas.

Assuming that the main program's cached thread pool is replaced with a fixed thread pool with parameter 3, the result is as follows: Why must 3 threads sell the apples before they sell bananas? We open 5 threads to sell apples, and 1 threads to sell bananas, but the fixed thread pool can only have up to 3 threads, so selling bananas is a task waiting in the queue. When these 3 threads sell all the apples, they will reuse 1 of the threads to sell the bananas. If we change the parameter to 6, it will be the same as the above result.

Summary: Different thread pools function differently, execute opens a thread to drive a task, shutdown () shuts down the thread pool to reclaim resources, but the task will still be executed in queue order (initiates an orderly shutdown in which Previously submitted tasks is executed), the task is waiting in the queue when the current number of threads is not enough to drive the task.

Java: Thread Pool Basics

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.