There are often tasks in the project that need to be asynchronous (submitted to the thread pool) to execute, and the main thread often needs to know the results of the asynchronous execution. Using runnable is not possible, we need to use callable to see the following code:
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
public class AddTask implements callable<integer> {
private int a,b;
Public AddTask (int a, int b) {
this.a = A;
this.b = b;
}
@Override public
Integer call throws Exception {
integer result = a + b;
return result;
}
public static void Main (string[] args) throws Interruptedexception, executionexception {executorservice
= Executors.newsinglethreadexecutor;
The JDK has so far returned all instances of Futuretask
future<integer> Future = executor.submit (New AddTask (1, 2));
Integer result = future.get;//The Get method returns only if the state of the future is completed (Future.isdone = True)
}
While it is possible to achieve the need for asynchronous execution results, we find that this future is actually very difficult to use because it does not provide a mechanism for notification, which means we don't know when future will be completed (if we need to poll isdone () to judge, it won't be necessary to do so). Look at the Java.util.concurrent.future.Future interface method:
Public interface Future<v> {
boolean mayinterruptifrunning);
Boolean iscancelled;
Boolean isdone;
V get throws Interruptedexception, Executionexception;
V get (long timeout, timeunit)
throws Interruptedexception, Executionexception, timeoutexception;
}
This shows that the future mechanism of JDK is actually not good, if you can add a listener to this future, let it in the completion of the notice when the listener is more useful, like the following ifuture:
Package future;
Import java.util.concurrent.CancellationException;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.TimeUnit;
/** * The result of a asynchronous operation. * * @author Lixiaohui * @param <V> Execution Result type parameters/public interface ifuture<v> extends future<v> {bo Olean issuccess; Whether success V Getnow; Returns the result immediately (regardless of whether future is in the completed state) Throwable cause; If the cause of the failure of the Boolean iscancellable; Whether the ifuture<v> await throws interruptedexception can be cancelled; Wait for the completion of the future Boolean await (long Timeoutmillis) throws interruptedexception;
Timeout waits for the completion of the future Boolean await (long timeout, timeunit timeunit) throws interruptedexception; Ifuture<v> awaituninterruptibly; Waits for future to complete, does not respond to interrupt Boolean awaituninterruptibly (Long Timeoutmillis),/timeout waits for future to complete, does not respond to interrupt Boolean
awaituninterruptibly (long timeout, timeunit timeunit); Ifuture<v> AddListener (ifuturelistener<v> L); When the future is complete, these added listeners are notified Ifuture<v> RemoveListener (IfutureliStener<v> l);
}
The next step is to implement this ifuture, before you explain the next Object.wait,object.notifyall method, because the core of the entire future implementation is the two methods. Look at the explanation in the JDK:
The public class Object {/** * causes the current thread-wait until another thread invokes the * {@link Java.lan
G.object#notify} method or the * {@link Java.lang.object#notifyall} to the this Object.
* In other words, this is behaves exactly as if it simply * performs the call {@code wait (0)}. * When this method is invoked, the current thread releases the object monitor lock and yields the CPU rights.
Until the other thread calls Notify/notifyall/public final void throws Interruptedexception {wait (0); }/** * wakes up all threads the are waiting on this object ' s monitor.
A * thread waits on an object ' s monitor by calling one of the * {@code wait} methods. * <p> * The awakened threads won't be able to proceed until the current * thread relinquishes the lock on t His object. The awakened threads * 'll compete in the usual manner and any other threads so might * is actively competing to Synchronize on this object; For example, * The awakened threads enjoy no reliable privilege or disadvantageIn * being the "next thread to lock" object.
* * Public final native void Notifyall;
}
Know this, we have to implement future also have the idea, when the thread calls Ifuture.await and other methods, if future is not completed, then call the Future.wait method to make the thread into the waiting state. When other threads set future to completion (note that the completion state here includes the normal end and the end of the exception), you need to call the Future.notifyall method to wake those threads that were in the waiting state before the wait method was invoked. The complete implementation is as follows (code should not be difficult to understand place, I am referring to Netty's future mechanism.) Interested can go to see the source code of Netty):
Package future;
Import java.util.Collection;
Import java.util.concurrent.CancellationException;
Import java.util.concurrent.CopyOnWriteArrayList;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.TimeUnit;
Import java.util.concurrent.TimeoutException; /** * <pre> * At the end of normal, if the result of the execution is not NULL, then result is executed; If execution is null, result = {@link abstractfuture#success_signal} * When the exception ends, result is an instance of {@link Causeholder}, and if the exception that is caused by the cancellation ends, then ResU It is an instance of {@link cancellationexception}, otherwise an instance of another exception * the following conditions cause an asynchronous operation to go from an incomplete state to a completed state, that is, to invoke the Notifyall method when the following occurs: * <ul> * Lt;li> Asynchronous Operation canceled (Cancel method) </li> * <li> asynchronous operation at the end of normal (Setsuccess method) </li> * <li> asynchronous operation at the end of the exception ( Setfailure method) </li> * </ul> * </pre> * * @author lixiaohui * * @param <V> * Type of the asynchronous execution result/p
Ublic class Abstractfuture<v> implements ifuture<v> {protected volatile Object result;//need to be sure of its visibility/** * Listener Set * * Protected collection<ifuturelistener<
v>> listeners = new copyonwritearraylist<ifuturelistener<v>>; /** * When the result of a task's normal execution is null, that is, when the client calls {@link abstractfuture#setsuccess (NULL)}, * results refers to the object/private static final successs
Ignal success_signal = new Successsignal;
@Override public boolean mayinterruptifrunning {if (isdone) {//completed cannot cancel return false;
} synchronized (this) {if (Isdone) {/double check return false;
result = new Causeholder (new cancellationexception); Notifyall; Isdone = True to notify the thread waiting in the object's wait notifylisteners;
Notifies the listener that the asynchronous operation has completed return true;
@Override public boolean iscancellable {return result = NULL; @Override public boolean iscancelled {return result!= null && result instanceof Causeholder && (
Causeholder). cause instanceof Cancellationexception;
@Override public boolean Isdone {return result!= null; @Override public V get throws Interruptedexception, executionexception {await;//wait for execution result throwable cause = cause;
if (cause = = null) {//No exception occurred, the asynchronous operation ended normally return getnow;
} if (cause instanceof cancellationexception) {//asynchronous operation was canceled throw (cancellationexception) cause; } throw new Executionexception (cause); Other exceptions} @Override public V get (long timeout, timeunit unit) throws Interruptedexception, Executionexception, timeout
Exception {if (await (timeout, unit)) {//timeout waits for execution result throwable cause = cause;
if (cause = = null) {//No exception occurred, the asynchronous operation ended normally return getnow;
} if (cause instanceof cancellationexception) {//asynchronous operation was canceled throw (cancellationexception) cause;
throw new executionexception (cause);//Other exception}//time to asynchronous operation has not finished, throw timeout exception throw new TimeoutException; @Override public boolean issuccess {return result = = null? false:!! (
Result instanceof Causeholder);
@SuppressWarnings ("unchecked") @Override Public v. Getnow {return (V) (result = = success_signal? null:result); @Override public throwable Cause {if!= null &Amp;& result instanceof Causeholder) {return ((Causeholder) result). cause;
return null; @Override public ifuture<v> AddListener (ifuturelistener<v> listener) {if (listener = null) {throw n
EW NullPointerException ("Listener");
} if (Isdone) {//If the Listener Notifylistener (listener) is directly notified of the completion;
return this;
} synchronized (this) {if (!isdone) {listeners.add (listener);
return this;
} notifylistener (listener);
return this; @Override public ifuture<v> RemoveListener (ifuturelistener<v> listener) {if (listener = null) {thro
W New NullPointerException ("Listener");
} if (!isdone) {listeners.remove (listener);
return to this;
@Override public ifuture<v> await throws interruptedexception {return await0 (true);
Private Ifuture<v> Await0 (Boolean interruptable) throws Interruptedexception {if (!isdone) {//If completed, returns directly If terminal is allowed and interrupted, throw interrupt exception if (interruptable && thread.interrupted) {THRow new Interruptedexception ("thread" + Thread.currentThread.getName + "has been interrupted.");
Boolean interrupted = false; Synchronized (this) {while (!isdone) {a try {wait;//release lock enters the waiting state, waiting for other threads to call the Notify/notifyall method} catch of this object (I
Nterruptedexception e) {if (interruptable) {throw e;
else {interrupted = true; if (interrupted) {//}}} {//Why do you want to set the interrupt flag bit here?
Because the interrupt flag is clear after returning from the wait method, it is reset here to let other code know that this is interrupted.
Thread.currentThread.interrupt;
} return this; @Override public boolean await (long Timeoutmillis) throws Interruptedexception {return await0 (Timeunit.millisecond
S.tonanos (Timeoutmillis), true); @Override public boolean await (long timeout, timeunit unit) throws Interruptedexception {return await0 (Unit.tonano
s (timeout), true); Private Boolean await0 (Long Timeoutnanos, Boolean interruptable) throws Interruptedexception {if (isdone) {return
True } if (Timeoutnanos <= 0) {return ISDONe
} if (interruptable && thread.interrupted) {throw new interruptedexception (toString); Long starttime = Timeoutnanos <= 0?
0:system.nanotime;
Long waittime = Timeoutnanos;
Boolean interrupted = false;
try {synchronized (this) {if (isdone) {true;
} if (waittime <= 0) {return isdone; for (;;)
{try {Wait (waittime/1000000, (int) (waittime% 1000000));
The catch (Interruptedexception e) {if (interruptable) {throw e;
else {interrupted = true;
} if (Isdone) {return true;
else {waittime = Timeoutnanos-(system.nanotime-starttime);
if (waittime <= 0) {return isdone;
}}}} finally {if (interrupted) {Thread.currentThread.interrupt;
@Override public ifuture<v> awaituninterruptibly {try {return await0 (false);
catch (Interruptedexception e) {//here if you throw an exception can not handle the throw new Java.lang.InternalError; }} @Override PuBlic boolean awaituninterruptibly (Long Timeoutmillis) {try {return await0 TimeUnit.MILLISECONDS.toNanos (Timeoutmilli
s), false);
catch (Interruptedexception e) {throw new Java.lang.InternalError; @Override public boolean awaituninterruptibly (long timeout, timeunit unit) {try {return await0 Unit.tonanos (t
Imeout), false);
catch (Interruptedexception e) {throw new Java.lang.InternalError;
} protected ifuture<v> Setfailure (Throwable cause) {if (SETFAILURE0 (cause)) {notifylisteners;
return this;
} throw new IllegalStateException ("Complete already:" + this);
Private Boolean setFailure0 (Throwable cause) {if (Isdone) {return false;
} synchronized (this) {if (Isdone) {return false;
result = new Causeholder (cause);
Notifyall;
return true;
} protected ifuture<v> setsuccess (Object result) {if (SETSUCCESS0) {//set to notify listener after successful notifylisteners;
return this; } throw new IllegalStateException ("compLete already: "+ this";
Private Boolean SETSUCCESS0 (Object result) {if (Isdone) {return false;
} synchronized (this) {if (Isdone) {return false;
} if (result = = NULL) {//asynchronous operation completed normally, null this.result = success_signal;
else {This.result = result;
} Notifyall;
return true;
private void Notifylisteners {for (ifuturelistener<v> l:listeners) {Notifylistener (L);
} private void Notifylistener (ifuturelistener<v> l) {try {l.operationcompleted (this);
catch (Exception e) {e.printstacktrace;
} private static class Successsignal {} private static final class Causeholder {final throwable cause;
Causeholder (Throwable cause) {this.cause = cause;
}
}
}
So how do you use this, with the above skeleton implementation, we can customize a variety of asynchronous results. The following simulates a delayed task:
Package future.test; Import future.
Ifuture; Import future.
Ifuturelistener; /** * Delay Addition * @author Lixiaohui * * * * * */public class Delayadder {public static void main (string[] args) {new Delayad Der.add (3 * 1000, 1, 2). AddListener (new ifuturelistener<integer> {@Override public void operationcompleted (I
Future<integer> Future) throws Exception {System.out.println (future.getnow);
}
}); /** * Delay plus * @param delay extension milliseconds * @param a addends * @param b addends * @return Asynchronous Results/Public Delayadditionfut
Ure Add (long delay, int a, int b) {delayadditionfuture future = new Delayadditionfuture;
New Thread (New Delayadditiontask (delay, A, B, future)). Start;
return future;
Private class Delayadditiontask implements Runnable {private long delay;
private int A, b;
Private Delayadditionfuture future;
Public Delayadditiontask (long delay, int a, int B, delayadditionfuture future) {super;
This.delay = delay;
THIS.A = A;
this.b = b; This.future = future;
@Override public void Run {try {thread.sleep (delay);
Integer i = a + b;
TODO here set Future to completion state (normal execution completed) future.setsuccess (i);
The catch (Interruptedexception e) {//TODO here sets the future as completion status (completion of exception execution) future.setfailure (e.getcause);
}}} package future.test; Import future.
Abstractfuture; Import future.
Ifuture; Just two ways to expose the public class Delayadditionfuture extends abstractfuture<integer> {@Override public ifuture<int
Eger> setsuccess (Object result) {return super.setsuccess (result);
@Override public ifuture<integer> setfailure (Throwable cause) {return super.setfailure (cause);
}
}
You can see the client does not have the initiative to ask future whether complete, but future completion of automatic callback operationcompleted method, the client only need to implement logic in the callback.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.