Java program execution Timeout--future interface Introduction

Source: Internet
Author: User

In Java, if you need to set the maximum time for code execution, which is time-out, you can use the Java thread pool Executorservice class with the future interface. The future interface is part of the Java Standard API in the Java.util.concurrent package. The future interface is the implementation of the Java thread's future pattern, which can be computed asynchronously.

The future mode can be described as follows: I have a task to give to the Future,future to complete this task for me. I can do anything I want to do during the period. After a while, I handy can take the results from the future. It is equivalent to an order form, after a period of time can take the order to pick up, this period can do anything else. One of the future interface is the order form, the real processing order is the executor class, which according to the requirements of the future interface to produce products.

The future interface provides a way to detect whether a task is executed, wait for the task to finish executing, or set a time-out for the task to execute. The way to timeout this setting is the key to implementing a Java program execution timeout.

The future interface is a generic interface, and the strict format should be Future<v>, where V represents the type of task return value that the future performs. The method of the future interface is described below:

    • A Boolean cancel (Boolean mayinterruptifrunning) cancels the execution of the task. parameter specifies whether the task execution is interrupted immediately, or the end of the task
    • Boolean iscancelled () The task has been canceled, and the task is canceled before it is completed correctly, returns true
    • Whether the Boolean isDone () task has completed. It is important to note that if a task terminates normally, an exception, or a cancellation, it will return true
    • V get () throws Interruptedexception, Executionexception waits for the end of the task execution and then obtains the result of type V. Interruptedexception thread is interrupted exception, executionexception task execution exception, if the task is canceled, will also throwCancellationException
    • V Get (long timeout, timeunit unit) throws Interruptedexception, Executionexception, timeoutexception As with the Get function above, the setting timeout time is more. The parameter timeout specifies the time-out period, the units of the uint specified times, and the associated definitions in the enumeration class Timeunit. If the calculation times out, TimeoutException will be thrown

The future realization class has java.util.concurrent.futuretask<v> namely javax.swing.swingworker<t,v>. Futuretask is often used to handle our tasks. The Futuretask class also implements the Runnable interface, so it can be directly submitted to executor execution. The code to implement time-outs using Futuretask is as follows:

Java code
  1. Executorservice executor = Executors.newsinglethreadexecutor ();
  2. futuretask<string> future =
  3. New Futuretask<string> (new callable<string> () {//using the callable interface as a construction parameter
  4. Public String Call () {
  5. //Real task is executed here, the return value type is string, can be any type
  6. }});
  7. Executor.execute (future);
  8. There's something else you can do here.
  9. try {
  10. result = Future.get (timeunit.milliseconds); //Get results, and set timeout execution time to 5 seconds. You can also use Future.get (), do not set the execution timeout time to get results
  11. } catch (Interruptedexception e) {
  12. Futuretask.cancel (true);
  13. } catch (Executionexception e) {
  14. Futuretask.cancel (true);
  15. } catch (TimeoutException e) {
  16. Futuretask.cancel (true);
  17. } finally {
  18. Executor.shutdown ();
  19. }

You can also use the Executorservice.submit method to obtain future objects without directly constructing future objects, and the Submit method supports the callable interface type, as well as the Runnable interface as a parameter, with great flexibility. Examples of use are:

Java code
    1. Executorservice executor = Executors.newsinglethreadexecutor ();
    2. futuretask<string> future = Executor.submit (
    3. New Callable<string> () {//Use callable interface as construction parameter
    4. Public String Call () {
    5. //Real task is executed here, the return value type is string, can be any type
    6. }});
    7. There's something else you can do here.
    8. The code that gets the result with the above

Implementing the Future Interface:

[Java]View PlainCopy
  1. Private class futuretest<v> implements future<v>{
  2. @Override
  3. Public Boolean Cancel (Boolean arg0) {
  4. //TODO auto-generated method stub
  5. return false;
  6. }
  7. @Override
  8. Public V Get () throws Interruptedexception, executionexception {
  9. //TODO auto-generated method stub
  10. return null;
  11. }
  12. @Override
  13. Public V Get (long arg0, Timeunit arg1) throws Interruptedexception,
  14. Executionexception, TimeoutException {
  15. //TODO auto-generated method stub
  16. return null;
  17. }
  18. @Override
  19. Public Boolean iscancelled () {
  20. //TODO auto-generated method stub
  21. return false;
  22. }
  23. @Override
  24. Public Boolean isDone () {
  25. //TODO auto-generated method stub
  26. return false;
  27. }
  28. }

Implement the Callbale interface:

[Java]View PlainCopy
    1. Private class callabletest<v> implements callable<v>{
    2. @Override
    3. Public V Call () throws Exception {
    4. //TODO auto-generated method stub
    5. return null;
    6. }
    7. }

Java program execution Timeout--future interface Introduction

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.