`

读FutureTask源码

阅读更多
//一个可以异步返回计算的结果
//它同时实现了Future和Runnable
//先看构造函数
 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

//运行runnable并返回给定的result
public FutureTask(Runnable runnable, V result) {
        //适配器模式转化runnable接口
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }

//适配器模式转化runnable接口
 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;
        }
    }



 public void run() {
        //如果state不等于0或者设置当前已经被其他线程占用了直接返回。
        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 = null;
            int s = state;
	    //如果被取消了
            if (s >= INTERRUPTING)
	    //让出执行权
                handlePossibleCancellationInterrupt(s);
        }
    }


//设定指定值
protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }


private void finishCompletion() {
        //释放所有等待线程
        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
    }


private void handlePossibleCancellationInterrupt(int s) {
       
        if (s == INTERRUPTING)
            while (state == INTERRUPTING)
                Thread.yield(); // wait out pending interrupt

    }

protected void done() { }

//获取结果
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();
		//超时删除q
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
		//挂起当前线程
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
    }

    private void removeWaiter(WaitNode node) {
        if (node != null) {
            node.thread = null;
            retry:
            for (;;) {          // restart on removeWaiter race
                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
                    s = q.next;
                    if (q.thread != null)
                        pred = q;
	            //到这里说明q.thread==null,q是需要删除的节点。
                    else if (pred != null) {
		        //修改上一个节点的next
                        pred.next = s;
			//上一个节点被删了,重新循环。
                        if (pred.thread == null) 
                            continue retry;
                    }
		    //走到这里说明第一个节点就是被删除的节点
                    else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                          q, s))
			//设置失败重新循环
                        continue retry;
                }
                break;
            }
        }
    }

//获取值
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);
    }

//在一定时间内等待获取结果超时抛出异常
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);
    }


//任务是否取消
public boolean isCancelled() {
        return state >= CANCELLED;
    }

//任务是否完成
 public boolean isDone() {
        return state != NEW;
    }


//试图取消任务的执行
public boolean cancel(boolean mayInterruptIfRunning) {
        //任务已经开始直接返回false
        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;
    }

//将结果设置为异常
 protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }


//执行计算但不设置结果执行完后重置
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 = null;
            s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
        return ran && s == NEW;
    }

分享到:
评论

相关推荐

    futuretask源码分析(推荐)

    主要介绍了futuretask源码分析(推荐),小编觉得还是挺不错的,这里给大家分享下,供各位参考。

    futuretask用法及使用场景介绍

    FutureTask用法及使用场景介绍 FutureTask是一种异步获取执行结果或取消执行任务的机制,它可以用来处理耗时的计算任务,使主线程不需要等待计算结果,而是继续执行其他任务。下面将详细介绍FutureTask的用法和使用...

    FutureTask学习

    `FutureTask`是Java并发编程中的一个重要组件,它位于`java.util.concurrent`包下,是`Executor`框架的一部分。这个类结合了`Runnable`或`Callable`接口的特性,并提供了异步执行的能力,同时允许你在任务完成后获取...

    FutureTask:FutureTask原始解析与重组-源码解析

    三,未来任务源码 FutureTask的七种状态 状态(state) 值 描述 新的 0 任务执行阶段,结果赋值值前 完成中 1个 结果赋值阶段 普通的 2个 任务执行完毕 优秀的 3 任务执行时发生异常 取消 4 任务被取消 中断 5 设置...

    spring线程池ThreadPoolExecutor配置以及FutureTask的使用

    在本篇文章中,我们将深入探讨`ThreadPoolTaskExecutor`的配置及其使用,并结合`FutureTask`来讨论异步任务处理。 首先,让我们了解`ThreadPoolTaskExecutor`的基本配置。在Spring中,我们通常通过在配置文件或Java...

    Java中的Runnable,Callable,Future,FutureTask的比较

    Java中的Runnable、Callable、Future和FutureTask是Java多线程编程中的核心概念,它们各自扮演着不同的角色,共同协作以实现并发任务的管理和执行。 1. **Runnable**: Runnable是最基本的多线程接口,它只有一个`...

    Java 多线程与并发(17-26)-JUC线程池- FutureTask详解.pdf

    #### 四、FutureTask源码解析 ##### 4.1 Callable接口 `Callable`是一个泛型接口,其泛型`V`指定了`call`方法返回的类型。与`Runnable`接口不同,`Callable`不仅能够执行任务,还能返回计算结果,并且可以抛出异常...

    揭密FutureTask.docx

    《揭密FutureTask:Java异步编程的核心工具》 在Java并发编程中,FutureTask扮演着至关重要的角色,它是实现异步计算的关键组件。本文将深入探讨FutureTask的原理和用法,帮助开发者更好地理解和利用这个强大的工具...

    Java线程池FutureTask实现原理详解

    Java线程池FutureTask实现原理详解 Java线程池FutureTask实现原理详解是Java多线程编程中的一种重要机制,用于追踪和控制线程池中的任务执行。下面将详细介绍FutureTask的实现原理。 类视图 为了更好地理解...

    比较java中Future与FutureTask之间的关系

    Future与FutureTask之间的关系 在Java中,Future和FutureTask都是用于获取线程执行的返回结果,但是它们之间存在一些差异和关联。本文将详细介绍Future和FutureTask的关系、使用和分析。 一、Future介绍 Future...

    Java FutureTask类使用案例解析

    Java FutureTask类使用案例解析 Java FutureTask类是一种异步计算的工具,用于执行长时间的任务并获取结果。它实现了Runnable和Future接口,既可以作为一个Runnable对象提交给Executor执行,也可以作为一个Future...

    FutureTask底层实现分析,有了FutureTask主线程要想获得工作线程(异步计算线程)的结果变得比较简单

    FutureTask 底层实现分析 FutureTask 是 Java 中的一种非常重要的多线程设计模式,用于异步计算线程之间的结果传递。在 JDK 中,FutureTask 类是 Future 模式的实现,它实现了 Runnable 接口,作为单独的线程运行。...

    java源码学习比较java源码学习比较

    比如,对比分析多个并发模型的实现(如线程池、FutureTask和CompletableFuture),既能理解并发编程的核心概念,也能掌握实际应用技巧。 最后,参与开源项目或阅读其他开发者提交的代码也是一种提升方式。这不仅...

    Java中Future、FutureTask原理以及与线程池的搭配使用

    Java中的`Future`和`FutureTask`是并发编程中重要的工具,它们允许程序异步执行任务并获取结果。`Future`接口提供了对异步计算结果的访问和控制,而`FutureTask`是`Future`的一个具体实现,它还同时实现了`Runnable`...

    简谈java并发FutureTask的实现

    Java并发编程中,`FutureTask`是一个非常关键的组件,它结合了`Runnable`和`Future`接口的能力,使得我们可以在异步执行的任务完成后获取其结果。`FutureTask`不仅是一个可取消的任务,还能报告其执行状态。在这个...

    Android(Java)之多线程结果返回——Future 、FutureTask、Callable、Runnable

    `Future`、`FutureTask`、`Callable`和`Runnable`是Java并发编程中的核心接口和类,它们在Android开发中同样有着广泛的应用。下面将详细介绍这些概念以及它们如何协同工作。 1. `Runnable`: 这是Java中最基础的多...

    Android游戏开发之多线程的操作方式源码

    6. **FutureTask**:与ExecutorService配合使用,可以获取异步任务的结果。 7. **RxJava/RxAndroid**:响应式编程库,提供了更高级的线程控制和数据流管理,适用于复杂的异步操作。 在实际开发中,合理地运用这些...

    性能极限漂移特技,只有头发少的人才知道.docx

    1. **FutureTask源码分析**:深入理解`FutureTask`的工作原理,包括状态管理、执行流程、取消机制等。 2. **手动实现FutureTask**:尝试自己动手实现一个简易版的`FutureTask`类,加深对其内部机制的理解。 3. **...

    Java并发包源码分析(JDK1.8)

    AQS相关应用(CountDownLatch、CyclicBarrier、Semaphore等),executor(ThreadPoolExecutor、ScheduledThreadPoolExecutor、FutureTask等),collection(ConcurrentHashMap、CopyOnWriteArrayList等), ...

Global site tag (gtag.js) - Google Analytics