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 throw
CancellationException
- 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
- Executorservice executor = Executors.newsinglethreadexecutor ();
- futuretask<string> future =
- New Futuretask<string> (new callable<string> () {//using the callable interface as a construction parameter
- Public String Call () {
- //Real task is executed here, the return value type is string, can be any type
- }});
- Executor.execute (future);
- There's something else you can do here.
- try {
- 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
- } catch (Interruptedexception e) {
- Futuretask.cancel (true);
- } catch (Executionexception e) {
- Futuretask.cancel (true);
- } catch (TimeoutException e) {
- Futuretask.cancel (true);
- } finally {
- Executor.shutdown ();
- }
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
- Executorservice executor = Executors.newsinglethreadexecutor ();
- futuretask<string> future = Executor.submit (
- New Callable<string> () {//Use callable interface as construction parameter
- Public String Call () {
- //Real task is executed here, the return value type is string, can be any type
- }});
- There's something else you can do here.
- The code that gets the result with the above
Implementing the Future Interface:
[Java]View PlainCopy
- Private class futuretest<v> implements future<v>{
- @Override
- Public Boolean Cancel (Boolean arg0) {
- //TODO auto-generated method stub
- return false;
- }
- @Override
- Public V Get () throws Interruptedexception, executionexception {
- //TODO auto-generated method stub
- return null;
- }
- @Override
- Public V Get (long arg0, Timeunit arg1) throws Interruptedexception,
- Executionexception, TimeoutException {
- //TODO auto-generated method stub
- return null;
- }
- @Override
- Public Boolean iscancelled () {
- //TODO auto-generated method stub
- return false;
- }
- @Override
- Public Boolean isDone () {
- //TODO auto-generated method stub
- return false;
- }
- }
Implement the Callbale interface:
[Java]View PlainCopy
- Private class callabletest<v> implements callable<v>{
- @Override
- Public V Call () throws Exception {
- //TODO auto-generated method stub
- return null;
- }
- }
Java program execution Timeout--future interface Introduction