Future & FutureTask

A, What

 1. java to create multi-threaded approach

   a. Thread, the result is not performed, neither the data nor abnormal

   b. ThreadPool, reducing the overhead of thread creation and destruction

   If the method returns a result to be obtained, the thread may be used or shared variables communication;. C Runnable, only one run () method, the result is not performed, is performed Thread

   d. Callable, only one call () method, is added Runnable, there is the return value is abnormal, returns a generic result

   e. Future, Mr. credentials as a result instead, the next operation is not blocked, then obtaining results credentials for asynchronous computation

2. FutureTask Future class implements the interface, a basic implementation of the Future

3. Examples can FutureTask Callable as a parameter, and creates an instance of FutureTask, as the Runnable this example, as an argument to start a thread

 

Two, How

1. Callable interface, with ExecutorService in the submit () method, in order to obtain the return value

2. Future interfaces, isDone () method to see if the asynchronous operation is completed, GET () method returns a result, for asynchronous

3. FutureTask类

a. implement the Runnable interface and Future interfaces, a combination of asynchronous and returns the result of the function

. B FutureTask object no return value is a Runnable; but the interior will be converted to a Callable Runnable, returns a value; final return value pick-get () method, rather than returning to

. C there is a callback function done (), will be triggered at the end of the task; and Future Without this feature, the task can only judge whether the end, and then manually

 

 

Third, usage scenarios (When)

1. The time-consuming calculations, the main thread to complete their task, and then get the results of sub-thread

2. Under high concurrency environment only once, such as the establishment of a database link

 

Four, Why (principle)

1. FutureTask status field, representing the status of the current thread

* Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int state;
    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

2. FutureTask the run () method source code, the logic is to perform call Callable main () method, the result is stored in a global variable, equivalent to a package of the Runnable

public  void RUN () {
         IF (! State NEW = || 
            ! UNSAFE.compareAndSwapObject ( the this , runnerOffset,
                                          null , Thread.currentThread ()))
             return ;
         the try { 
            a Callable <V> C = Callable; // Callable here is the method of construction from the inside of the successor, although examples are FutureTask the Runnable, but ultimately using a Callable 
            IF (C =! null && State == NEW) { 
                V Result; 
                Boolean RAN;
                 the try { 
                    Result = c.call ();
                    RAN = to true ; 
                } the catch (the Throwable EX) { 
                    Result = null ; 
                    RAN = to false ; 
                    setException (EX); // save the call exception thrown, rather than directly thrown 
                }
                 IF (RAN) 
                    SET (Result); / / save the results of a method call 
            } 
        } the finally {
             // Runner MUST BE non-null settled to an until State iS
             // Prevent Concurrent Calls to RUN ()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

 3. get () method source code, using an infinite loop obstruction, until I got the results from the global variables in

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
}

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
}

 

 

 

reference:

https://www.cnblogs.com/cz123/p/7693064.html

https://www.jianshu.com/p/bce9301f1adb

 

Guess you like

Origin www.cnblogs.com/june0816/p/7077405.html