How Java implements Task timeout processing

Source: Internet
Author: User

Task timeout processing is a common requirement, such as when doing more time-consuming operations (such as network requests) or when taking up some of the more valuable resources (such as database connections), we usually need to set a time-out for these operations and terminate the operation and reclaim resources when the execution time exceeds the set threshold. There are two ways to handle time-out tasks in Java: One is based on time-outs of asynchronous task results, and one is to use a deferred task to terminate a timeout operation. Details are provided below.

A. Timeout acquisition based on asynchronous task results

The results of asynchronous task-based fetching is usually used with the thread pool, and when we submit a task to the thread pool, we return a future object, and when we call the Get method of the future, we can set a time-out and throw an exception if the task is not finished before the set time. Next look at the code:

 Public classFuturedemo {StaticExecutorservice executorservice= Executors.newfixedthreadpool (Runtime.getruntime (). AvailableProcessors ());  Public Static voidMain (string[] args) { future<String> future = Executorservice.submit (NewCallable<string>() {@Override PublicString Call () {Try{TimeUnit.SECONDS.sleep (10); } Catch(interruptedexception e) {System.out.println ("The task was interrupted. "); }                return"OK";        }        }); Try{String result= Future.get (2, Timeunit.seconds); } Catch(Interruptedexception | executionexception |timeoutexception e) {Future.cancel (true); System.out.println ("Task timed out. "); }finally{System.out.println ("Cleans up resources. "); }    }}

Run the code with the output as follows:

Second, use the delay task to terminate the timeout operation

Another way to implement a task timeout is to set a timer before the task is submitted, which cancels the task after the set interval. Of course, if the task is completed within the specified time, remember to cancel the timer. First look at our worker threads:

 Public classRunningtask {Private volatile BooleanIsstop;  Public voidStop () { This. isstop=true; }     Public voiddoing () {intI=1;  while(!isstop) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(Interruptedexception e) {}} System.out.println ("The task was interrupted. "); }}

This worker thread checks the Isstop variable every second, so we can cancel the task by isstop the variable. As for the logic of canceling the task we put in the timer, the code is as follows:

 Public class Implements Runnable {    private  runningtask runningtask;      Public Canceltask (Runningtask runningtask) {        this. Runningtask= runningtask;    }    @Override    publicvoid  run () {        runningtask.stop ();    }}

As you can see, the function of this timer is to interrupt the operation of the worker thread after a certain amount of time. Next Test:

 Public classScheduledemo {StaticScheduledexecutorservice executorservice= Executors.newscheduledthreadpool (Runtime.getruntime (). Availableprocessors () * *);  Public Static voidMain (string[] args) {runningtask runningtask=NewRunningtask (); Scheduledfuture<?> scheduledfuture = Executorservice.schedule (NewCanceltask (Runningtask), 3, Timeunit.seconds);        Runningtask.doing (); if(!Scheduledfuture.isdone ()) {Scheduledfuture.cancel (true); }    }}

The results of the operation are as follows:

As you can see, the task can also be canceled after a timeout.

How Java implements Task timeout processing

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.