Java ThreadPool thread pool simple analysis

Source: Internet
Author: User

Five types of thread pool creation are available in the Java 1.5 Concurrent toolkit:

Executorservice Executor=executors.newcachedthreadpool (); Executorservice Cacheexecutor=executors.newcachedthreadpool (New Testthreadfactory ()); Executorservice Fixexecutor=executors.newfixedthreadpool (10); Executorservice Fixedexecutor=executors.newfixedthreadpool (Ten, New Testthreadfactory ()); Executorservice Sigexecutor=executors.newsinglethreadexecutor (); Executorservice Singleexecutor=executors.newsinglethreadexecutor (New Testthreadfactory ()); Scheduledexecutorservice Schexecutor=executors.newscheduledthreadpool (10); Scheduledexecutorservice Scheduledexecutor=executors.newscheduledthreadpool (10,new TestThreadFactory ()); Scheduledexecutorservice Ssexecutor=executors.newsinglethreadscheduledexecutor (); Scheduledexecutorservice Sigschexcutor=executors.newsinglethreadscheduledexecutor (New TestThreadFactory ());

The underlying implementation principle is basically the same: when the new thread pool generates a task queue (blockqueue<runnable>), the first execute () or the Submit () method creates a looping thread, Used to repeatedly read the task in the queue and execute it (PS: The first commit task is not to go into the task queue, directly by the created thread), the subsequent execute () or the submit () operation directly commits the runnable task into the queue. When the queue is empty, The loop thread is blocked by the Blockqueue take () method.

Singlethreadexecutor is actually a special case of Fixedthreadpool, singlethreadexecutor specifies that there is only one thread in the same queue to iterate through the queue task and execute it, Fiexedthreadpool can specify multiple threads for the same queue to iterate through the queue task and execute.

Newfixedthreadpool (10) generates 10 threads to read the same task queue, but the 10 threads are not generated at the same time, but instead commit a task (that is, execute an execute () or submit () method) to produce one, when the number of tasks submitted exceeds 10, The 11th task is submitted directly to the blockqueue<runnable> queue, which is then fetched and executed by a thread from one of the 10 threads. The 10 threads generated by Fixedthreadpool will not be recycled to 9, and not more likely to be increased to 11.

Cachethreadpool does not specify a specific number of threads to read and only perform tasks in the task queue, but it has a maximum number of threads (integer.max_value=2 32 times-1), and when task queue saturation is unable to insert a new task, A new thread is automatically generated to perform the newly inserted task and is involved in reading the saturated task queue and executing. If 10 threads are generated during peak periods, the trough period requires only one thread to execute, The remaining 9 threads are terminated after they have survived for a certain period of time. The time to live is one minute. This is to be distinguished from the fixedthreadpool.

The number of threads in the Scheduledthreadpool thread pool also needs to be pre-specified, and its main feature is that queue tasks are read and executed on a scheduled delay

No matter what thread, when the task queue increases the speed of the queue read execution, it is possible to create a task loss, the probability of loss from low to High is

Cachethreadpool > Newfixedthreadpool > Singlethreadexecutor, this is a good understanding. In this case, program defaults to throw out rejectedexecutionexception exceptions

The new thread pool is another construction parameter threadfactory, the main purpose is to make a simple encapsulation of the submitted task.


Attach a few core code snippets

    public void Execute (Runnable command) {        if (command = = null)            throw new NullPointerException ();        if (poolsize >= corepoolsize | |!addifundercorepoolsize (command)) {            if (runstate = = RUNNING && workqueue.o Ffer (command)) {                if (runstate! = RUNNING | | poolsize = = 0)                    ensurequeuedtaskhandled (command);            }            else if (!addifundermaximumpoolsize command)                reject (command);//is shutdown or saturated        }    }

    Private Boolean addifundercorepoolsize (Runnable firsttask) {        Thread t = null;        Final Reentrantlock mainlock = This.mainlock;        Mainlock.lock ();        try {            if (Poolsize < corepoolsize && Runstate = = RUNNING)                t = addthread (firsttask);        } finally {
   
    mainlock.unlock ();        }        if (t = = null)            return false;        T.start ();        return true;    }
   

    Private Thread Addthread (Runnable firsttask) {        worker w = new Worker (firsttask);        Thread t = threadfactory.newthread (w);        if (t! = null) {            w.thread = t;            Workers.add (w);            int nt = ++poolsize;            if (NT > Largestpoolsize)                largestpoolsize = NT;        }        return t;    }

/** * Runs A single task between Before/after methods.            */private void RunTask (Runnable Task) {final Reentrantlock runlock = This.runlock;            Runlock.lock ();  try {/* * Ensure that unless pool are stopping, this thread * does not has Its interrupt set. This requires a * double-check of state in case the interrupt is * cleared concurrently W                 ITH a shutdownnow--if so, * the interrupt is re-enabled.                    */if (Runstate < STOP && thread.interrupted () &&                Runstate >= STOP) thread.interrupt (); /* Track execution state to ensure, AfterExecute * is called only if task completed or threw * exception. Otherwise, the caught runtime exception * would have been thrOwn by AfterExecute itself, in * which-case we don ' t want to call it again.                */Boolean ran = false;                BeforeExecute (thread, Task);                    try {task.run ();                    ran = true;                    AfterExecute (task, NULL);                ++completedtasks;                    } catch (RuntimeException ex) {if (!ran) AfterExecute (task, ex);                Throw ex;            }} finally {Runlock.unlock (); }}/** * Main run loop */public void run () {try {Runnab                Le task = Firsttask;                Firsttask = null; while (task! = NULL | |                    (Task = Gettask ()) = null) {runTask (Task);                task = null;            }} finally {Workerdone (this); }        }




Java ThreadPool thread pool simple analysis

Related Article

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.