Executorservice thread pool usage

Source: Internet
Author: User
After Java 5, the concurrent thread has undergone a fundamental change. The most important thing is a bunch of new APIs for starting, scheduling, and managing threads. After Java 5, it is better to use executor to start a thread than to use thread start. Among the new features, the thread startup, execution, and shutdown processes can be easily controlled, and the features of the thread pool can be easily used. 1. Create a taskA task is a class that implements the runnable interface. The actual run method can be used during creation. Ii. Execute the taskThe Java. util. Concurrent. executorservice interface object is used to execute tasks. This interface object is created through the static method of Java. util. Concurrent. executors in the tool class. Executors the executor, executorservice, and scheduledexecutorservice defined in this package , Threadfactory and callable class factory and practical methods.Executorservice provides a way to manage termination and generate a future for tracking the execution of one or more asynchronous tasks. You can disable executorservice, which causes it to stop accepting new tasks. After the program is closed, it is terminated. At this time, no task is being executed, No task is waiting for execution, and a new task cannot be submitted. Executorservice.exe cute (New testrunnable (); 1. Create an executorservice by using a static method of the tool class java. util. Concurrent. executors. Executors the executor, executorservice, and scheduledexecutorservice defined in this package , Threadfactory and callable class factory and practical methods.For example, to create an executorservice instance, executorservice is actually a management tool for a thread pool: executorservice = executors. newcachedthreadpool (); executorservice = executors. newfixedthreadpool (3); executorservice = executors. newsinglethreadexecutor (); 2. Add a task to a thread for execution. When a task is added to the thread pool, the thread pool creates a thread for each task, this thread will be automatically executed at a later time. 3. Close the execution service objectExecutorservice. shutdown (); 5. After obtaining the return value of a task execution, the task is divided into two types: one is the class that implements the runnable interface and the other is the class that implements the callable interface. Both can be executed by executorservice, but the runnable task has no return value, while the callable task has a return value. Besides, the call () method of callable can only use the (<t>
And returns a <t>, indicating that the task is waiting for completion. Public interface Callable <v>

A task that returns results and may throw exceptions. The implementer defines a method called call without any parameters.

The callable interface is similar to that of classes whose instances may be executed by another thread. However, runnable does not return results and cannot throw a checked exception.

Class contains some practical methods to convert from other common forms to callable classes. The call () method in callable is similar to the runnable run () method, that is, the former has a return value, and the latter does not. When a callable object is passed to the submit method of executorservice, the call method is automatically executed on a thread and the execution result future object is returned. Similarly, if the runnable object is passed to the submit method of executorservice, the run method is automatically executed on a thread and the execution result future object is returned, however, if the get method is called on the future object, null is returned. Unfortunately, in the Java API documentation, this section is very confusing. It is probably because the translators have not figured it out yet. Or the comment is not in place. The following is an example: Import java. util. arraylist;
Import java. util. List;
Import java. util. Concurrent .*;

Publicclass callabledemo {
Publicstaticvoid main (string []
ARGs ){
Executorservice = executors. newcachedthreadpool ();
List <future <string> resultlist = new arraylist <future <string> ();

// Create and execute 10 tasks
For (INT I = 0; I <10; I ++ ){
// Executorservice is used to execute callable tasks and save the results in the future variable.
Future <string> future = executorservice. Submit (New taskwithresult (I ));
// Store the task execution result to the list
Resultlist. Add (future );
}

// Traverse the task result
For (Future <string> FS: resultlist ){
Try {
System. Out. println (FS. Get (); // print the execution results of each thread (task)
} Catch (interruptedexception e ){
E. printstacktrace ();
} Catch (executionexception e ){
E. printstacktrace ();
} Finally {
// Start and close the task in sequence, and execute the previously submitted task, but do not accept the new task. If it is disabled, the call has no other effect.
Executorservice. Shutdown ();
}
}
}
}

Class taskwithresult implements callable <string> {
Privateint ID;

Public taskwithresult (int id ){
This. ID = ID;
}

Public String call () throws exception {
The system. Out. println ("Call () method is automatically called. Work !!! "+ Thread. currentthread (). getname ());
// Simulate a time-consuming operation
For (INT I = 999999; I> 0; I --);
The Return "Call () method is automatically called and the result of the task is:" + ID +"
"+ Thread. currentthread (). getname ();
}
} Running result: the call () method is automatically called. Work !!! Pool-1-thread-1
The call () method is automatically called. Work !!! Pool-1-thread-3
The call () method is automatically called. Work !!! Pool-1-thread-4
The call () method is automatically called. Work !!! Pool-1-thread-6
The call () method is automatically called. Work !!! Pool-1-thread-2
The call () method is automatically called. Work !!! Pool-1-thread-5
The call () method is automatically called. The result of the task is: 0 pool-1-thread-1.
The call () method is automatically called. The result of the task is: 1 pool-1-thread-2.
The call () method is automatically called. Work !!! Pool-1-thread-2
The call () method is automatically called. Work !!! Pool-1-thread-6
The call () method is automatically called. Work !!! Pool-1-thread-4
The call () method is automatically called. The result of the task is 2 pool-1-thread-3.
The call () method is automatically called. Work !!! Pool-1-thread-3
The call () method is automatically called, and the result of the task is: 3 pool-1-thread-4
The call () method is automatically called. The result of the task is 4 pool-1-thread-5.
The call () method is automatically called. The result of the task is 5 pool-1-thread-6.
The call () method is automatically called. The result of the task is 6 pool-1-thread-2.
The call () method is automatically called. The result of the task is 7 pool-1-thread-6.
The call () method is automatically called. The task result is: 8 pool-1-thread-4.
The call () method is automatically called. The result of the task is: 9 pool-1-thread-3.

Several different executorservice thread pool objects

1. newcachedthreadpool () -Cache pool, first check whether there are any threads in the pool that have been previously established. If yes, reuse it. If not, create a new thread to join the pool.
-Cache pools are usually used to execute asynchronous tasks with short lifetime.
 Therefore, some connection-oriented daemon-type servers are rarely used.
-The Reuse thread must be a thread in the pool of timeout idle. The default timeout value is 60 s. If the idle length is exceeded, the thread instance will be terminated and removed from the pool.
 Note: The thread placed in the cachedthreadpool does not have to worry about its termination. If it exceeds the timeout, it is automatically terminated.
2. newfixedthreadpool -The newfixedthreadpool is similar to the cachethreadpool and can be used for reuse, but cannot be used to create new threads at any time.
-Its uniqueness: at any time point, only a fixed number of active threads can exist. If a new thread needs to be created, it can only be placed in another queue for waiting, until the termination of a thread in the current thread is directly removed from the pool
-Unlike cachethreadpool, fixedthreadpool does not have an idle mechanism (it may also exist, but since the document is not mentioned, it must be very long, such as relying on the upper layer's TCP or UDP idle mechanism ), therefore, most fixedthreadpool targets some very stable and fixed regular concurrent threads, which are mostly used on servers.
-From the source code of the method, the cache pool and fixed pool call the same underlying pool, except that the parameters are different:
The number of threads in the fixed pool is fixed, and the value is 0 seconds idle (no idle)
The number of threads in the cache pool supports 0-integer.max_value (obviously, the host's resource capacity is not fully considered), and the idle is 60 seconds. 
3. scheduledthreadpool -Scheduling Thread Pool
-The threads in this pool can be delay in sequence by schedule or periodical.
4. singlethreadexecutor -Singleton thread. There can only be one thread in any time pool
-It uses the same underlying pool as the cache pool and fixed pool, but the number of threads is 1-seconds (no idle)

The preceding four thread pools use the default thread factory of executor to create threads. You can also define your own thread factory separately.
The following is the default thread factory code:

   Static class defaultthreadfactory implements threadfactory {
       Static final atomicinteger poolnumber = new atomicinteger (1 );
       Final threadgroup group;
       Final atomicinteger threadnumber = new atomicinteger (1 );
       Final string nameprefix;

       Defaultthreadfactory (){
           Securitymanager S = system. getsecuritymanager ();
           Group = (s! = NULL )? S. getthreadgroup (): thread. currentthread (). getthreadgroup ();
          
           Nameprefix = "pool-" + poolnumber. getandincrement () + "-thread -";
       }

       Public thread newthread (runnable R ){
           Thread t = new thread (group, R, nameprefix + threadnumber. getandincrement (), 0 );
           If (T. isdaemon ())
               T. setdaemon (false );
           If (T. getpriority ()! = Thread. norm_priority)
               T. setpriority (thread. norm_priority );
           Return T;
       }
   }

You can also customize threadfactory and add it to the pool creation parameters.

 Public static executorservice newcachedthreadpool (threadfactory ){



Execute () method of executor
The execute () method adds the runnable instance to the pool and performs some pool size calculation and priority processing.
The execute () method itself is defined in the executor interface. Multiple implementation Classes define different execute () methods.
For example, the execute method of the threadpoolexecutor class (cache, fiexed, and single pools are called) is as follows:

   Public void execute (runnable command ){
       If (command = NULL)
           Throw new nullpointerexception ();
       If (poolsize> = corepoolsize |! Addifundercorepoolsize (command )){
           If (runstate = running & workqueue. Offer (command )){
               If (runstate! = Running | poolsize = 0)
                   Ensurequeuedtaskhandled (command );
           }
           Else if (! AddifundermaximumpoolsizE (command ))
               Reject (command); // is shutdown or saturated
       }
   }

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.