Thread pool - Dependent Interface

  The whole system thread pool involves three threads and related interface and a thread pool and related interfaces.

Executor

public interface Executor {

    void execute(Runnable command);
}

 

   Top-level interface to the thread pool, there is only one method. execute method accepts a Runnable type of task and execute the task at some point in the future, it is possible to perform the task using a thread pool thread is also possible with the new thread.

  • It is to execute not submit
  • Runnable rather than the type of the parameter is associated interface and Future

 

Future

  Future interfaces in the Java world is a placeholder for the implementation of the results of all top-level asynchronous interfaces, not only in the thread pool in Netty is also widely used. For an asynchronous method, the method call will return immediately, regardless of whether the method is finished, it is necessary to Future As a result of the method placeholder, and with the Future obtain whether asynchronous method execution is completed and the results obtained when finished, as well as cancel asynchronous execution methods.

  • boolean cancel (boolean mayInterruptIfRunning) tries to cancel a task being performed, if the task has been finished or some method can not be canceled, returns false. If the task is executing, based on the value of mayInterruptIfRunning to decide whether interruption task. In fact, cancel by interrupt threads to achieve, it needs to be interrupted thread to provide appropriate support. When a task is successfully cancel, isDone isCancelled returns true
  • V get () throws InterruptedException, ExecutionException; wait until the task is finished retrieval results, which should be a method of blocking
  • V get (long timeout, TimeUnit unit) and get similar, but joined the timeout mechanism
  • boolean isCancelled (); if the task was canceled
  • boolean isDone (); task is finished, complete and not to be understood as also returns after a task is true isDone cancel, even if the task is not completed
public interface Future<V> {

 
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

 

 Runnable

  Old friends, nothing to say

  • Runnable no generics
  • run method does not return value, nor does it provide Future # get results similar to the method for obtaining the results if you want to get the thread of shared variables must pass similar manner
public interface Runnable {
    public abstract void run();
}

 

 

Callable

  New faces, and are similar to Runnable to be used when a new thread

  • Callable return value
  • Callable throws an exception
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

 

 

FutureTask

  In real use to a thread pool class, note that this is a class that implements the interface instead of the interface Future indirectly achieved Callable and Future interfaces. Its main role

  • Future provides an implementation of the interface, the results can be acquired by the get method, public cancel set interrupt flag. And the get method is blocked until the completion of the implementation of the method will not return.
  • A Callable and Runnable task object wrapped (wrap), the task submit the thread pool and no direct interface to achieve the Future, but the thread pool to perform tasks strategy is asynchronous, necessarily need to use the Future interface, so it is necessary before the actual execution method the Runnable and Callable object package for asynchronous nature objects FutureTask

State variables

  Each FutureTask object represents a submit the task, because FutureTask may occur during the execution of a lot of changes, such as finished, quit unexpectedly, is cancel and so on, so the need for a state to a state change stored FutureTask in the implementation process. The state is volatile, so changes to the state is certainly the CAS.

  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;

  And these state that all possible values ​​are int, so the execution can be determined by comparing the size of the state FutureTask way.

 
public boolean isCancelled() {
    return state >= CANCELLED;
}
public boolean isDone() {
    return state != NEW;
}

 

 

Mission

  The mission FutureTask, the result of a task into the outcome.

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // 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);
        }
    }

 

FutureTask get results

  If FutureTask of State <= the COMPLETING, explained FutureTask not yet finished, call the get method of thread should block and wait, or else call the report returns the result.  

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

 

  Similar threads and blocking threads ideas AQS blocking calls get methods, maintaining a queue, create Node join the queue when the thread is blocked, then park the current thread.

  • awaitDone may be multiplexed with the get timeouts, so there into the reference time and the associated parameters, if the incoming time-out is not considered timed = false.
  • awaitDone is interrupted sensitive, that call get suspended if interrupted thread will return immediately, reflecting the first piece of code in the for loop, checking Thread interrupt flag is set if an exception is thrown and returned.
  • Queued way is to use CAS, because there may be multiple threads simultaneously calling the get method is suspended and added to the queue, we need to consider the safety of concurrency.
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);
        }
    }

 

  If the state> = COMPLETING, described FutureTask finished, the results can be returned directly. In fact, it is the outcome method strong turn about.

private V report(int s) throws ExecutionException {
    Object x = outcome;
    if (s == NORMAL)
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    throw new ExecutionException((Throwable)x);
}

 

 

Cancel mission

  • First modify the status of FutureTask. NEW state is only time will according to the value of the state mayInterruptIfRunning modified to INTERRUPTING or CANCELLED. If the state is not NEW failure or CAS will return false, CAS failed only because the state is judged NEW CAS and modify state has changed between. In short can only cancel NEW state of FutureTask.
  • After the success of CAS modified state, in  the case of mayInterruptIfRunning set to true thread interrupt flag. this.runner FutureTask is an attribute, representing the currently executing thread Callable tasks.
  • Call finishCompletion delete all calls due to get on the waiting task thread.
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }

 

Guess you like

Origin www.cnblogs.com/AshOfTime/p/10963133.html