Several thread pools in the Java package introduce __java

Source: Internet
Author: User
Introduction to several thread pools in Java encapsulation Fixedthreadpool

Fixedthreadpool is not a class, it is a Threadpooleexcutor object of a fixed number of threads created by the Executors tool class, and there are 2 ways to implement it.

Executors.newfixedthreadpool (3)//fixed 3 threads number

Executors.newfixedthreadpool (3, executors.defaultthreadfactory ()) ;

Let's look at the internal implementation of Newfixedthreadpool ().

public static Executorservice newfixedthreadpool (int nthreads) {
    //Here you can see that a Treadpoolexecutor object is returned, However, this object is equal to the number of core threads and the maximum number of threads return
    new Threadpoolexecutor (Nthreads, Nthreads,
                              0L, Timeunit.milliseconds,
                              new Linkedblockingqueue<runnable> ());
}


public static Executorservice newfixedthreadpool (int nthreads, threadfactory threadfactory) {return
    new Threadpoolexecutor (Nthreads, Nthreads,
                                  0L, Timeunit.milliseconds,
                                  new linkedblockingqueue<runnable> (),
                                  //compared to the above method, is more threadfactory parameter
                                  threadfactory);

newfixedthreadpool () analysis

Here we use a parameter method to analyze. Both Corepoolsize and maxpoolsize are parameter nthreads: The thread pool is a core thread and is nthraeds when there is no non-core thread. A non-worker thread survives 0: When a core thread finishes a task in a queue, the core thread dies if there is no task in the queue. The system resources are saved to a great extent. The default maximum number of queues used is integer.max_value: The queue length is the maximum int, which is equivalent to infinity, so that no matter how many tasks you have, you can store them in the queue, waiting for the core thread to execute.

the execution of a task in a thread pool is roughly divided into 4 phases .

1. The number of tasks is less than the number of core threads, and if you are performing a new task, create a core thread to perform the task.

2. When the core thread is performing the task, the task is not performed and is less than the queue length, which is where the task is stored in the queue.

3. When the core threads are performing tasks and the number of tasks that are not performed is greater than the queue length, this is a non-core thread that performs a new task.

4. When the core threads are performing tasks, and the number of tasks that are not performed is greater than the queue length, and the Non-core threads are performing tasks, the saturation strategy is applied.

The thread pool created by Newfixedpoolexecutor () will not have a 3rd phase.

fixedpoolexecutor Usage Scenarios :

Fixedthreadpool applies to scenarios where the current number of threads needs to be limited to meet the requirements of resource management, and it applies to servers with heavy workloads. Singlethreadpool

Singlethreadpool is a thread pool of only one threads, the internal implementation is the same as Fixedthreadpool, but the number of threads is different.

Singlethreadpool Method of Invocation

Executors.newsinglethreadexecutor ();

Executors.newsinglethreadexecutor (Executors.defaultthreadfactory ());

Internal implementation of Singlethreadpool

public static Executorservice Newsinglethreadexecutor () {return
    new Finalizabledelegatedexecutorservice (
                            New Threadpoolexecutor (1, 1,
                                0L, Timeunit.milliseconds,
                                new Linkedblockingqueue<runnable> ()));


public static Executorservice Newsinglethreadexecutor (Threadfactory threadfactory) {return
    new Finalizabledelegatedexecutorservice
        (New Threadpoolexecutor (1, 1,
                                0L, Timeunit.milliseconds,
                                New) Linkedblockingqueue<runnable> (),
                                threadfactory));

We see that the new Finalizabledelegatedexecutorservice () object wraps a Threadpoolexecutor object, This Threadpoolexecutor object is actually a thread of Fixedthreadpool, And the Finalizabledelegatedexecutorservice class is the threadpoolexecutor in the encapsulation of a layer.

So we can also simply understand that Singlethreadpool is only one thread of Fixedthreadpool. Cachedthreadpool

Cachedthreadpool Method of Invocation

Executors.newcachedthreadpool ();

Executors.newcachedthreadpool (Executors.defaultthreadfactory ());

Internal implementation of Cachedthreadpool

public static Executorservice Newcachedthreadpool () {return
    new Threadpoolexecutor (0,integer.max_value,
                              60L , Timeunit.seconds,
                              new synchronousqueue<runnable> ());


public static Executorservice Newcachedthreadpool (Threadfactory threadfactory) {return
    new Threadpoolexecutor (0, Integer.max_value,
                                  60L, Timeunit.seconds,
                                  new synchronousqueue<runnable> (),
                                  threadfactory);

The Threadpoolexecutor object parameter Analysis in Newcachedthreadpool () corepoolsize the number of core threads is 0 maxpoolsize the maximum number of threads is integer.max_value. KeepAliveTime: Non-worker threads live 60 seconds Workqueue: Synchronousqueue used by queues (Synchronousqueue is a queue with no capacity).

Through the parameters we can know that there is no core number of threads, then the first phase of the thread pool will not go, the synchronousqueue queue is an not-capacity blocking queue. Each insert operation must wait for a corresponding removal from another thread.

Below is a look at the execution diagram of the Cachedthreadpool Execute () method:

1.execute () First executes Synchronousqueue.offer (Runnable R). If there is an idle thread in the current Maxpool, the Synchronousqueue.poll (KeepAliveTime, timeunit.nanoseconds) is executed, then the main thread (Invoke execute () Thread) to perform an offer operation paired with the poll operation performed by the idle thread. The main thread gives the task to the idle thread to execute and the Execute () method completes.

2. When Maxpool is empty, or if there are currently no idle threads in Maxpool, there will be no thread execution Synchronousqueue.poll (KeepAliveTime, timeunit.nanoseconds). In this case, step 1 fails. At this point cachedthreadpool creates a new thread to perform the task and execute () execution completes.

3. In step 2, the newly created thread executes the Synchronousqueue.poll (KeepAliveTime, Timeunit.nanoseconds) after the task has finished executing. This poll operation will allow the idle thread to wait for up to 60 seconds in the Synchronousqueue, if the main thread in 60 seconds commits a new task (the main thread executes step 1), then the idle thread will perform the new task of the main thread commit; otherwise, this idle thread will terminate. Because idle threads that are idle for 60 seconds are terminated, cachedthreadpool that remain idle for a long time will not use any resources.

Cachedthreadpool is a large, unbounded thread pool, for small programs that perform very short asynchronous tasks, or for lighter-load servers. Scheduledthreadpoolexecutor

Scheduledthreadpoolexecutor is a subclass of Threadpoolexecutor.

Scheduledthreadpooleexcutor's call has 4 of the form

Executors.newscheduledthreadpool (3);

Executors.newscheduledthreadpool (3, Executors.defaultthreadfactory ());

New Scheduledthreadpoolexecutor (3);

New Scheduledthreadpoolexecutor (3, Executors.defaultthreadfactory ());

In fact, the internal implementation of the Executors.newscheduledthreadpool (3) method also creates an object directly, such as:

public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {return
    new Scheduledthreadpoolexecutor (corepoolsize);
}


public static Scheduledexecutorservice Newsinglethreadscheduledexecutor (Threadfactory threadfactory) {return
    New Delegatedscheduledexecutorservice
        (new Scheduledthreadpoolexecutor (1, threadfactory));
}

So let's look at the next step. The construction method implementation of Scheduledthreadpoolexecutor ()

Public scheduledthreadpoolexecutor (int corepoolsize) {
    super (corepoolsize, Integer.max_value,
          default_ Keepalive_millis, milliseconds,
          new Delayedworkqueue ());
}


Public scheduledthreadpoolexecutor (int corepoolsize,threadfactory threadfactory) {
    super (corepoolsize, Integer.max_value,
          default_keepalive_millis, milliseconds,
          new Delayedworkqueue (), threadfactory);

As you can see from the construction method, in fact, Scheduledthreadpoolexecutor calls the construction method in the parent class, that is, the construction in Threadpoolexecutor. So let's say the parameters passed in: corepoolsize: Core threads, incoming default maximum number of threads is integer.max_value. The retention time defaults to 10 milliseconds, default_keepalive_millis default 10L, unit milliseconds. The queue used is Delayedworkqueue,delayedworkqueue is an endless queue, which increases the length of the queue when the added task is greater than the queue. At the same time, Delayedworkqueue also has a set of algorithm in ascending order of timeout, following the principle of "the left node is smaller than the right one (the next time it executes less)." Specific details are explained in the next chapter.

Through construction we can know that Scheduledthreadpoolexecutor and threadpoolexecutor are not much different, the biggest difference is the difference between queues. Because the length of the delayedworkqueue has an increasing type and a sorting algorithm in ascending order of time, the scheduledthreadpoolexecutor has the characteristics of delaying the task.

Because the Delayedworkqueue is a unbounded queue, the maximum number of threads set Integer.max_value is not used.

how to execute Scheduledthreadpoolexecutor

Because Scheduledthreadpoolexecutor inherits from Threadpoolexecutor, there will be execute () and submit (), which do not describe these 2 methods.

Scheduledthreadpoolexecutor, in addition to inheriting Threadpoolexecutor, also implements the Scheduledexecutorservice interface

Scheduledexecutorservice interface method

Creates a task and executes the public
scheduledfuture<?> schedule (Runnable command, long delay, and Timeunit unit) after a given delay time;

Ditto, except that the parameters are callable public
<V> scheduledfuture<v> Schedule (callable<v> callable, long delay, Timeunit unit);

/**
 * Parameter initialdelay: The time for the first delay
 * parameter period: Indicates the time interval between the start of task execution and the start of the next task * * Public
scheduledfuture< ?> scheduleatfixedrate (Runnable command, long initialdelay, long period, timeunit unit);

/**
 * Parameter initialdelay: The time for the first delay
 * parameter period: Indicates the time interval between the end of task execution and the start of the next task * * Public                                 
scheduledfuture <?> schedulewithfixeddelay (Runnable command, long initialdelay, long delay, timeunit unit);                                            

Schedule () method implementation code:

Public scheduledfuture<?> Schedule (Runnable command,long delay,timeunit unit) {
    if (command = NULL | | unit = = N ull)
        throw new NullPointerException ();

    The 2nd parameter of Decoratetask () is the return value, which is the Task object runnablescheduledfuture<void> t = Decoratetask that is about to be deferred
    (command,new Scheduledfuturetask<void> (command, Null,triggertime (delay, unit), sequencer.getandincrement ());

    Delayedexecute (t);/delayed execution of this task return
    t;
}

Decoratetask () Implementation code
protected <V> runnablescheduledfuture<v> decoratetask (Runnable Runnable, Runnablescheduledfuture<v> Task) {return
    task;
}

Scheduledthreadpoolexecutor's execution method is very similar to the timer timer.

scheduledthreadpoolexecutor Simple use of schedule ()

public class Test {public
    static void Main (string[] args) {
        scheduledthreadpoolexecutor Scheduledthreadpoolexecutor = new Scheduledthreadpoolexecutor (3);

        SYSTEM.OUT.PRINTLN ("Before Task Execution time:" + system.currenttimemillis ());//Before Task Execution time: 1496847975977

        Scheduledthreadpoolexecutor.schedule (New Runnable () {
            @Override public
            void Run () {
                System.out.println ( "Task Execution Time:" + system.currenttimemillis ())//Task Execution time: 1496847976993
            }
        }, 1000, timeunit.milliseconds);
    }
Use of Scheduleatfixedrate ()
public class Test {public
    static void Main (string[] args) {
        scheduledthreadpoolexecutor Scheduledthreadpoolexecutor = new Scheduledthreadpoolexecutor (3);

        SYSTEM.OUT.PRINTLN ("Before Task Execution time:" + system.currenttimemillis ());

        Scheduledthreadpoolexecutor.scheduleatfixedrate (New Runnable () {
            @Override public
            void Run () {
                SYSTEM.OUT.PRINTLN ("Task Execution time:" + system.currenttimemillis ());
                try {
                    thread.sleep (1000);//This is for distinction and next method
                } catch (Interruptedexception e) {
                    e.printstacktrace ();
                }
            }
        , 1000, 5000, timeunit.milliseconds);
    }


Console print Results:

1496848166272 Task Execution time
: 1496848167285     //First execution, task delay 1 seconds perform
task execution time: 1496848172281     //Every 5 seconds after task
execution time: 1496848177280 task Execution time:
1496848182282
Task Execution time: 1496848187282
Use of Schedulewithfixeddelay ()
public class Test {public static void main (string[] args) {SCHEDULEDTHREADPOOLEXECU

        Tor scheduledthreadpoolexecutor = new Scheduledthreadpoolexecutor (3); SYSTEM.OUT.PRINTLN ("Before Task Execution time:" + system.currenttimemillis ());//Before Task Execution time: 1496847975977 SCHEDULEDTHREADPOOLEXECUTOR.S Chedulewithfixeddelay (New Runnable () {@Override public void run () {SYSTEM.OUT.PR
                INTLN ("Task Execution time:" + system.currenttimemillis ());
                try {thread.sleep (1000);
                catch (Interruptedexception e) {e.printstacktrace ();
    }}, 1000, 5000, timeunit.milliseconds); Print results: 1496848595162 task Execution Time: 1496848596181//First time delay task, delay 1 seconds Task Execution time: 1496848602188//2nd time task, delay about 6 seconds (5 seconds is Delay time, 1 seconds is the time spent on task execution: 1496848608204 task Execution time: 1496848614211 task Execution time: 1496848620231 task Execution time: 1496848626256 

Scheduledthreadpoolexecutor Stop Method shutdown () Shutdownnow ()

These two methods were introduced when the thread pool was threadpoolexecutor. Singlethreadscheduledexecutor

Singlethreadscheduledexecutor and Scheduledthreadpoolexecutor have the same characteristics as delayed execution tasks. Singlethreadscheduledexecutor's internal implementation is scheduledthreadpoolexecutor, except that there is only one core thread (although there is a maximum number of threads, but the queue has no boundaries, so in addition to the core thread, Other threads do not perform tasks).

Call to Singlethreadscheduledexecutor

Executors.newsinglethreadscheduledexecutor ();

Executors.newsinglethreadscheduledexecutor (Executors.defaultthreadfactory ());

Internal implementation of Singlethreadscheduledexecutor

public static Scheduledexecutorservice Newsinglethreadscheduledexecutor () {return new Deleg
Atedscheduledexecutorservice (New Scheduledthreadpoolexecutor (1)); public static Scheduledexecutorservice Newsinglethreadscheduledexecutor (Threadfactory threadfactory) {return new
Delegatedscheduledexecutorservice (New Scheduledthreadpoolexecutor (1, threadfactory)); }

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.