FutureTask类浅析

#概述 FutureTask类是可取消式异步计算方法。该类是Future接口的基本实现。可以开启和取消异步计算,查询异步计算结果是否完成,并且抽取出计算结果。计算结果只能在异步计算完成后被获取。异步计算一旦完成,计算将不能被重新开始和取消。除非计算过程的调用使用了runAndReset方法。 Callable和Runnable类都能够包装成FutureTask类。FutureTask本身实现了Runnable接口,并能够被提到Executor中去执行。 作为独立的类,其内部有protested方法用于执行任务。 #静态方法块

    try {
    //使用了unsafe设置state、runner和waiters的字段偏移量。
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> k = FutureTask.class;
            stateOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("state"));
            runnerOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("runner"));
            waitersOffset = UNSAFE.objectFieldOffset
                (k.getDeclaredField("waiters"));
        } catch (Exception e) {
            throw new Error(e);
        }

#任务运行状态 在FutureTask类中任务的运行状态设置为七种。 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; 任务运行状态之间的转换如下:

  NEW -> COMPLETING -> NORMAL
  NEW -> COMPLETING -> EXCEPTIONAL
  NEW -> CANCELLED
  NEW -> INTERRUPTING -> INTERRUPTED

#重要字段 //可执行任务 private Callable<V> callable; //异步计算结果或者get方法抛错信息 private Object outcome; // non-volatile, protected by state reads/writes //执行任务的线程 private volatile Thread runner; //等待线程队列 private volatile WaitNode waiters;

#重要方法 ##构造

  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) {
 //将runnable wrapper成callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

##任务取消

 public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

取消任务方法接收了一个布尔类型的变量 1、如果变量为true,则首先尝试将运行状态设置为interrupting,如果不允许则返回false,标示取消失败。否则获得任务,做中断操作,将对象的状态字段置为INTERRUPTED。 2、如果变量为false或者未设置,则直接尝试将任务状态置为cancelled,如果失败则返回false,表示取消失败。否则执行finishCompletion(),将所有线程队列中等待的线程全部释放掉。等待gc回收。 ##执行(任务不能被打断)

   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或者设置当前线程为执行线程操作失败,则返回空。 然后获得任务callable,如果任务状态是new并且任务非空,则调用call()方法获得结果,如果在异步计算的过程中抛异常则将返回null的结果。 最后继续获得任务执行状态,如果任务处于INTERRUPTING状态,则处理中断。

##任务执行(允许reset)

 protected boolean runAndReset() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return false;
        boolean ran = false;
        int s = state;
        try {
            Callable<V> c = callable;
            if (c != null && s == NEW) {
                try {
                    c.call(); // don't set result
                    ran = true;
                } catch (Throwable ex) {
                    setException(ex);
                }
            }
        } 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
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

和前一个run方法不同的有两个地方。第一个就是增加了一个boolean变量ran,第二个就是没有设置result。 ##获得结果

public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

获得结果的方法首先判断时间单位,如果未设置会抛空指针。然后获得任务运行状态,如果状态是未完成,并且等待指定时间后让然没有获得结果,则跑超时异常,否则运行 report(s)。

 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);
    }
    

report(s)方法会判断任务执行状态,根据状态是normal还是cancelled分别返回执行结果或异常信息。

转载于:https://my.oschina.net/zjItLife/blog/668232

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值