对于多线程,最早的jdk使用的都是runnable接口,其中的run方法是没有返回值的。
后来就加入了callable接口:
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;
}
允许有返回值。但是别忘了这是多线程环境下,这个返回值远没有那简单。因为我们的任务实现了callable接口,然后被异步调用,这个返回值怎么返回就是一个问题了。或者说,这个获取返回值的操作与任务本身的执行肯定是两个线程了。而且只有任务执行成功了才会有返回值,如果抛异常了就没有返回值。这个返回值与任务执行的状态息息相关。必然需要有一个组件来维护这任务的执行状态。那么谁来维护呢?
jdk就针对callable接口的返回值设计了另一个接口也即Future接口,来负责返回值的维护,或者更准确地说,获取任务的执行状态。
package java.util.concurrent;
/**
* A {@code Future} represents the result of an asynchronous
* computation. Methods are provided to check if the computation is
* complete, to wait for its completion, and to retrieve the result of
* the computation. The result can only be retrieved using method
* {@code get} when the computation has completed, blocking if
* necessary until it is ready. Cancellation is performed by the
* {@code cancel} method. Additional methods are provided to
* determine if the task completed normally or was cancelled. Once a
* computation has completed, the computation cannot be cancelled.
* If you would like to use a {@code Future} for the sake
* of cancellability but not provide a usable result, you can
* declare types of the form {@code Future<?>} and
* return {@code null} as a result of the underlying task.
*
* <p>
* <b>Sample Usage</b> (Note that the following classes are all
* made-up.)
* <pre> {@code
* interface ArchiveSearcher { String search(String target); }
* class App {
* ExecutorService executor = ...
* ArchiveSearcher searcher = ...
* void showSearch(final String target)
* throws InterruptedException {
* Future<String> future
* = executor.submit(new Callable<String>() {
* public String call() {
* return searcher.search(target);
* }});
* displayOtherThings(); // do other things while searching
* try {
* displayText(future.get()); // use future
* } catch (ExecutionException ex) { cleanup(); return; }
* }
* }}</pre>
*
* The {@link FutureTask} class is an implementation of {@code Future} that
* implements {@code Runnable}, and so may be executed by an {@code Executor}.
* For example, the above construction with {@code submit} could be replaced by:
* <pre> {@code
* FutureTask<String> future =
* new FutureTask<String>(new Callable<String>() {
* public String call() {
* return searcher.search(target);
* }});
* executor.execute(future);}</pre>
*
* <p>Memory consistency effects: Actions taken by the asynchronous computation
* <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a>
* actions following the corresponding {@code Future.get()} in another thread.
*
* @see FutureTask
* @see Executor
* @since 1.5
* @author Doug Lea
* @param <V> The result type returned by this Future's {@code get} method
*/
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;
}
这便是future接口的api。
通过future接口,我们可以取消任务的执行,判断执行的状态,获取返回值。
所以总结一下future接口的作用:提供了获取异步任务执行状态的接口。其实,这已经不仅仅是针对callable接口了,runnable接口也适用。
下面看一下future接口的唯一实现类futuretask类:
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
futuretask实现了runnable接口和future接口。那么它的定位就很明显了,首先一个futuretask肯定是一个task,可以被执行,其次它提供了获取执行状态的接口。
futuretask实际上一种特殊的task。我们自己定义的task会实现runnable或者callable接口,这种是静态的task,只是表明要做什么。但是futuretask是动态的task,会记录或者维持task执行的状态,类似于进程与程序的区别。所以futuretask必定在内部实现了一些关于执行状态维护的共有逻辑,然后通过future接口暴露出来。这些逻辑就在run方法里面实现,这也是为什么futuretask实现runnable接口的原因。所以它是介于线程与用户定义的静态task之间的概念,会持有静态task的引用,会维护执行状态,这些会在下面介绍。以往直接用thread对象嵌套静态任务的方式执行多线程,就无法维护任务执行的状态,这里引入一个中间层,封装了通用的方法,使得future接口可以实现
先看一下成员变量:
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
可以看到,futuretask把用户定义的静态任务作为成员变量存起来,并且用一个object类型的变量存储结果。waiters表示获取结果时阻塞的节点。
还有一个表示执行状态的变量:
* 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;
状态是一个task的重要特征。
下面是构造方法:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
futuretask会假定用户定义的任务必定有返回值。如果没有那么就必须提供一个,也就是针对runnable的情况,最终也会适配出一个callable。下面是源码:
public static <T> Callable<T> callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter<T>(task, result);
}
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) {
this.task = task;
this.result = result;
}
public T call() {
task.run();
return result;
}
}
接着就是futuretask最核心的部分了,看一下run方法是如何维护状态的:
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);
}
}
首先判断这个任务的状态是否是new,再看是否有线程执行这个任务了,也就是说一个futuretask不能有两个线程同时执行。因为有状态的概念,每一个futuretask描述的是一个静态任务的执行情况,所以同一时间只能被一个线程执行,否则状态就不唯一了。判定可以执行后就去执行任务,然后设置结果。下面是set方法:
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
这里也是使用cas操作,把状态修改了,同时给结果赋值。看一下finish:
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
这里做了什么?主要是如果任务没有执行完,那么调用get的线程会被阻塞,这里就是唤醒这些阻塞的线程的。可以结合get方法:
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);
}
}
只要状态不是结束,每一次get都会阻塞,阻塞就会创建一个新的node,实际上会阻塞在这个node上。
最后看一下cancel方法:
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;
}
其实就是通过打断执行任务的线程来实现的。
整体就是这样,线程阻塞逻辑还是值得深入研究的。