java并发编程实战-44-Future源码解析----cas---------------二周目---太具体的原理就不看了

Future的源码

使用方法:

FutureTask:

Callable和Runable的区别:

这个东西存在的意义就是线程去干  我去拿结果可以

 public FutureTask(Callable<V> callable) {
//我们对比理解下
//错误的东西但是好理解FutureTask是Runnable Callable是run 里面是run的实现
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

Callable的执行流程。

看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();
//看到这个call方法不是线程去调用的是我们去调用的,
//就是callable去调用的。等价关系看下面的图片,就是一个在线程中的耗操作。
//是在线程中的耗时操作
                    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);
        }
    }

类似于这个耗时操作是没有开线程的:

看代码,call方法是run方法去调用的,所以是线程中的耗时操作。

run方法是线程调用的。

注意FutureTask还有一个构造方法:

public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

我们可以大胆的猜想一下:

Callable其实是可以由Runnable和result组合在一起的。

看下这个callable方法: 

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

点进去看下这个RunnableAdapter

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

在这个接口中就实现了call方法,实际上就是执行了run方法。

-------

在看下状态:

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;

根据这个应用的代码

FutureTask<Integer> task = new FutureTask<>(call);//这个就相当于runnable
		Thread thread = new Thread(task);
		thread.start();

仔细研究下run方法,研究下FutureTask的run方法。因为这个是继承Runnable的。

public void run() {
        if (state != NEW ||//先进来状态肯定是new
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))//把当前的线程设置进来。第一个参数就是当前的对象  第二个参数就是本地的偏移量 第三个参数就是我们看到  第四个参数就是修改的值 偏移量和我们预期看到了不一样就不修改 返回false。cas获得当前的线程给此类的属性赋值
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();//看到这个call方法不是线程去调用的是我们去调用的,就是callable去调用的。就是一个在线程中的耗操作。
                    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);
        }
    }

看这个方法:

  protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

为NEW状态变为COMPLETING状态。

代码:

这里我们理解下一个cas操作:compareAndSwapObject

package com.roocon.thread.tb9;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Created by yangyu on 16/11/24.
 */
public class TestUnsafe {

    public static void main(String[] args) {
        Node node = new Node();//node是无参构造传的是null有参呢?
        Node nodeNext = new Node();//node是无参构造传的是null有参呢?
        /**
         * 通过CAS方法更新node的next属性
         * 原子操作
         */
//        boolean flag = node.casNext(null,nodeNext);
//        System.out.println(flag);
//        flag = node.casNext(nodeNext,new Node());
//        System.out.println(flag);

        //模拟下并发时候的更新
        new Thread(new Runnable(){
            public  void run(){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean flag = node.casNext(null,nodeNext);
                System.out.println(flag);
            }
        }).start();

        new Thread(new Runnable(){
            public  void run(){
                while(true){
                    boolean flag = node.casNext(nodeNext,new Node());//比较相等就说明没有别的线程去修改就可以愉快的更新 传入的是我们看到的值就是总线的值
                    System.out.println(flag);
                    if(flag){
                        break;
                    }
                }
            }
        }).start();

    }

    private static class Node{

        volatile Node next;

        /**
         * 使用Unsafe CAS方法
         * @param cmp 目标值与cmp比较,如果相等就更新返回true;如果不相等就不更新返回false;
         * @param val 需要更新的值;
         * @return
         */
        boolean casNext(Node cmp, Node val) {
            /**
             * compareAndSwapObject(Object var1, long var2, Object var3, Object var4)
             * var1 操作的对象
             * var2 操作的对象属性  这是是本地的值变为本地的偏移量
             * var3 var2与var3比较,相等才更新  这个是我们看到的值就是总线的值
             * var4 更新值
             */
            return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
        }

        private static final sun.misc.Unsafe UNSAFE;
        private static final long nextOffset;

        static {
            try {
                UNSAFE = getUnsafe();//获得可Unsafe
                Class<?> k = Node.class;//获得Node
                nextOffset = UNSAFE.objectFieldOffset
                        (k.getDeclaredField("next"));//获得newt属性  获得偏移量
            } catch (Exception e) {
                throw new Error(e);
            }
        }

        /**
         * 获取Unsafe的方法
         * 获取了以后就可以愉快的使用CAS啦
         * @return
         */
        public static Unsafe getUnsafe() {
            try {
                Field f = Unsafe.class.getDeclaredField("theUnsafe");//获取theUnsafe属性
                f.setAccessible(true);//可以访问私有的属性
                return (Unsafe)f.get(null);//返回属性的值
            } catch (Exception e) {
                return null;
            }
        }
    }
}

再看这个方法,如果正常执行就set

if (ran)
                    set(result);
   protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;//把结果放在outcome里面去
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();//这个就相当于图片里面的notifyAll
        }
    }

等价于这个方法:

 private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {//目前没有get线程不需要等待的节点的。
                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
    }

13.37

set就完事了。这个就是调用run方法放入过程。

-------

接下来调用get方法。

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);//没完成状态等待
        return report(s);
    }

不带超时时间的get方法。

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

带超时时间的get方法。

看下这个方法:

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);
    }
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);//等着了
        }
    }

 第一个线程。

下面是第二个线程:

 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) //等会再进来   //死循环第二次进来了
                Thread.yield();//让出spu资源 处于就绪状态
            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);
        }
    }

  没看懂。

  此时链表挂上等待的节点。

  set方法叫醒了。

 

 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);//叫醒当前的thread
                    }
                    WaitNode next = q.next;//叫醒下一个节点
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }

-------------------------------------------------tb9---------------------------------------------------------

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值