Java Executorservice life cycle

Source: Internet
Author: User
Tags execution sleep thread stringbuffer

The Executorservice interface inherits the executor interface and defines some lifecycle methods

Public interface 

Executorservice extends Executor {    
void shutdown ();    
List<runnable> Shutdownnow ();    
Boolean IsShutDown ();    
Boolean isterminated ();    
Boolean awaittermination (long timeout, timeunit unit)    
        throws interruptedexception;    
}

In this article, we analyze each of the methods inside.

First, we need to create a task code that basically randomly generates a string containing 10 characters.

/** 
 * Randomly generated 10-character string 
 * @author dream-victor * * */Public
class Task1 implements Callable<string > {  
      
    @Override public
    String call () throws Exception {  
        string base = " abcdefghijklmnopqrstuvwxyz0123456789 ";  
        Random Random = new Random ();  
        StringBuffer sb = new StringBuffer ();  
        for (int i = 0; i < i++) {int number  
            = Random.nextint (Base.length ());  
            Sb.append (Base.charat (number));  
        }  
        return sb.tostring ();  
    }  
      

And then we need a long task, where we default to sleep for 10 seconds

/** * 
 long time Task 
 *  
 * @author dream-victor * */Public
class LongTask implements callable< string> {  
      
    @Override public
    String call () throws Exception {  
        TimeUnit.SECONDS.sleep);  
        Return "Success";  
    }  
      

OK, all previous preparations are complete, let's take a look at these methods in the Executorservice interface that are related to the lifecycle:

1, Shutdown method: This method will smooth off the executorservice, when we call this method, Executorservice stop accepting any new tasks and wait for the completed task execution (the submitted task will be divided into two categories: a class is already After execution, the other class is not yet started, and the Executorservice will be closed when all the committed tasks have been completed. Here we first do not cite examples below.

2, Awaittermination method: This method has two parameters, one is timeout is the timeout time, the other is unit, time units. This method causes the thread to wait for the timeout to be long, and when the timeout time is exceeded, the executorservice is monitored for shutdown and returns true if it is closed or false. It is generally used in combination with the Shutdown method. For example:

Executorservice service = Executors.newfixedthreadpool (4);  
Service.submit (New Task1 ());  
Service.submit (New Task1 ());  
Service.submit (New LongTask ());  
Service.submit (New Task1 ());  
      
Service.shutdown ();  
      
while (!service.awaittermination (1, timeunit.seconds)) {  
    System.out.println ("thread pool not closed");  
}  
SYSTEM.OUT.PRINTLN ("Thread pool is closed");

In this code, we present a lengthy task for the third time, which will perform a 10-second slumber, followed by a shutdown () method, assuming that the executorservice is immediately closed and the following calls Service.awaittermination ( 1, Timeunit.seconds) method should return true, the program execution result should only print out: "Thread pool is closed." However, the actual results of the operation are as follows:

Thread pool does not close  
thread  
pool not closed thread pool no shutdown thread pool No shutdown thread pool No shutdown thread pool No shutdown thread pool No shutdown thread pool not closed Thread pool is closed

This means that we assume the error, service.awaittermination (1, timeunit.seconds) monitors the Executorservice shutdown every second, and the long task takes exactly 10 seconds to execute, As a result, the first 9 seconds of monitoring is executorservice, and the 10th second is closed, so the output at 10th seconds: The thread pool is closed. This also validates the condition that the shutdown method closes the Executorservice.

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.