JUC锁框架——LockSupport应用以及源码分析

LockSupport用法

在没有LockSupport之前,线程的挂起和唤醒咱们都是通过Object的wait和notify/notifyAll方法实现,而Object的wait和notify/notifyAll方法只能在同步代码块里用。而LockSupport的park和unpark无需同步代码块里,直接调用就可以了。

    public static void main(String[] args)throws Exception {
        Thread t1 = new Thread(()->{
            int sum = 0;
            for(int i=0;i<10;i++){
                sum+=i;
            }
            LockSupport.park();
            System.out.println(sum);
        });
        t1.start();
        Thread.sleep(1000);//等待t1中的求和计算完成,当我们注释此行时,则会导致unpark方法先于park方法。但是程序依然能够正确执行。
        LockSupport.unpark(t1);
    }

注意:我们在调用Object的notify和wait方法时如果notify先于wait方法那么程序将会无限制的等下去,而如果LockSupport的unpark方法先于park方法则不会无限制的等待。程序依然能够正确的执行

LockSupport比Object的wait/notify有两大优势:

  • LockSupport不需要在同步代码块里 。所以线程间也不需要维护一个共享的同步对象了,实现了线程间的解耦。
  • unpark函数可以先于park调用,所以不需要担心线程间的执行的先后顺序。

LockSupport在ThreadPoolExecutor中的应用1

1、首先我们创建一个线程池并执行FutureTask任务。

public static void main(String[] args)throws Exception {
        ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(1000);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5,5,1000, TimeUnit.SECONDS,queue);
        Future<String> future = poolExecutor.submit(()->{//此任务实现了Callable接口
            TimeUnit.SECONDS.sleep(5);
            return "hello";
        });
        String result = future.get();//同步阻塞等待线程池的执行结果。
        System.out.println(result);
    }

2、future.get()是如何阻塞当前线程并获取线程池的执行结果?

public <T> Future<T> submit(Callable<T> task) {
    if (task == null) throw new NullPointerException();
    RunnableFuture<T> ftask = newTaskFor(task);//查看源码其实是创建了一个FutureTask对象
    execute(ftask);
    return ftask;
}

protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    return new FutureTask<T>(callable);
}

通过上面的代码我们可以看出,其实当我们调用future.get()方法其实是调用FutureTask的get()方法。

//判断当前任务是否执行完毕,如果执行完毕直接返回任务结果,否则进入awaitDone方法阻塞等待。
public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

关于FutureTask源码分析具体可以查看https://my.oschina.net/cqqcqqok/blog/1982375

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);//调用parkNanos方法阻塞线程
            }
            else
                LockSupport.park(this);//调用park方法组塞住当前线程。
        }
    }

3、从前面的分析我们知道了当调用future.get()方法是如何阻塞线程,那么当任务执行完成之后如何唤醒线程的呢?

由于我们提交的任务已经被封装为了FutureTask对象,那么任务的执行就是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 {
                    //c.call()就是执行我们提交的任务,任务执行完后调用了set方法,进入set方法发现set方法调用了finishCompletion方法
                    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() {
        // 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);//通过cas操作将所有等待的线程拿出来,然后便使用LockSupport的unpark唤醒每个线程。
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }
        done();
        callable = null;        // to reduce footprint
    }

LockSupport在ThreadPoolExecutor中的应用2

您有没有这样的一个疑问,当线程池里没有任务时,线程池里的线程在干嘛呢?如果读过线程池源码(https://my.oschina.net/cqqcqqok/blog/2049249 )那么你一定知道,在线程getTask()获取任务的时候,如果没有新的任务那么线程会调用队列的take方法阻塞等待新任务。那队列的take方法是不是也跟Future的get方法实现一样呢?我们以ArrayBlockingQueue为例,来看一下源码实现。

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();//此处调用了Condition的await方法
        return dequeue();
    } finally {
        lock.unlock();
    }
}

继续看源码

public final void await() throws InterruptedException {
    if (Thread.interrupted()) throw new InterruptedException();
    Node node = addConditionWaiter();
    int savedState = fullyRelease(node);
    int interruptMode = 0;
    while (!isOnSyncQueue(node)) {
        LockSupport.park(this);//调用了LockSupport的park方法
        if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
            break;
    }
    if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
        interruptMode = REINTERRUPT;
    if (node.nextWaiter != null) // clean up if cancelled
        unlinkCancelledWaiters();
    if (interruptMode != 0)
        reportInterruptAfterWait(interruptMode);
}

LockSupport的实现

park和unpark简单介绍

LockSupport其实是一个简单的代理类,它里面的代码都是使用Unsafe类里面的native方法,这里可以简单看看sun.misc.Unsafe 本文主要学习里面的park和unpark方法。

在Unsafe里面,park和unpark分别如下定义:

//isAbsolute代表传入的time是绝对时间还是相对时间
public native void park(boolean isAbsolute, long time);
public native void unpark(Object thread);

unpark函数为线程提供“许可(permit)”,线程调用park函数则等待“许可”。这个有点像信号量,但是这个“许可”是不能叠加的,“许可”是一次性的。可以理解为设置一个变量0,1之间的切换。

如果线程B连续调用了多次unpark函数,当线程A调用park函数就使用掉这个“许可”,如果线程A第二次调用park,则进入等待状态。

注意,unpark函数可以先于park调用。比如线程B调用unpark函数,给线程A发了一个“许可”,那么当线程A调用park时,它发现已经有“许可”了,那么它会马上再继续运行,也就是不会阻塞。

而如果线程A处于等待许可状态,再次调用park,则会永远等待下去,调用unpark也无法唤醒。

下面先看LockSupport里面的park和unpark定义:

public static void park(Object blocker) {
    //获取当前运行线程
    Thread t = Thread.currentThread();
    //设置t中的parkBlockerOffset(挂起线程对象的偏移地址)的值为blocker
    //这个字段可以理解为专门为LockSupport而设计的,它被用来记录线程是被谁堵塞的,当程序出现问题时候,通过线程监控分析工具可以找出问题所在。注释说该对象被LockSupport的getBlocker和setBlocker来获取和设置,且都是通过地址偏移量方式获取和修改的。由于这个变量LockSupport提供了park(Object parkblocker)方法。
    setBlocker(t, blocker);
    //阻塞线程
    UNSAFE.park(false, 0L);
    //线程被释放,则将parkBlockerOffset设为null
    setBlocker(t, null);
}

public static void unpark(Thread thread) {
    if (thread != null)
        UNSAFE.unpark(thread);
}

park和unpark的c++实现

首先,包含park和unpark的头函数在:http://hg.openjdk.java.net/jdk8u/jdk8u40/hotspot/file/68577993c7db/src/share/vm/runtime/park.hpp 而其具体实现函数则在:http://hg.openjdk.java.net/jdk8u/jdk8u40/hotspot/file/95e9083cf4a7/src/os/solaris/vm/os_solaris.cpp

void Parker::park(bool isAbsolute, jlong time) {
 //_counter字段,就是用来记录“许可”的。
 //先尝试能否直接拿到“许可”,即_counter>0时,如果成功,则把_counter设置为0
  if (_counter > 0) {
      _counter = 0 ;
      OrderAccess::fence();
      //直接返回
      return ;
  }
  //获取当前线程
  Thread* thread = Thread::current();
  assert(thread->is_Java_thread(), "Must be JavaThread");
  JavaThread *jt = (JavaThread *)thread;
  //如果中途已经是interrupt了,那么立刻返回,不阻塞
  if (Thread::is_interrupted(thread, false)) {
    return;
  }
  //记录当前绝对时间戳
  timespec absTime;
  //如果park的超时时间已到,则返回
  if (time < 0) { // don't wait at all
    return;
  }
  if (time > 0) {
  //更换时间戳
    unpackTime(&absTime, isAbsolute, time);
  }
   //进入安全点,利用该thread构造一个ThreadBlockInVM。
  ThreadBlockInVM tbivm(jt);
  if (Thread::is_interrupted(thread, false) ||
      os::Solaris::mutex_trylock(_mutex) != 0) {
    return;
  }
  //记录等待状态
  int status ;
  //中途再次给予了许可,则直接返回不等带。
  if (_counter > 0)  { // no wait needed
    _counter = 0;
    status = os::Solaris::mutex_unlock(_mutex);
    assert (status == 0, "invariant") ;
    OrderAccess::fence();
    return;
  }
#ifdef ASSERT
  sigset_t oldsigs;
  sigset_t* allowdebug_blocked = os::Solaris::allowdebug_blocked_signals();
  thr_sigsetmask(SIG_BLOCK, allowdebug_blocked, &oldsigs);
#endif
  OSThreadWaitState osts(thread->osthread(), false /* not Object.wait() */);
  jt->set_suspend_equivalent();
#if defined(__sparc) && defined(COMPILER2)
  if (ClearFPUAtPark) { _mark_fpu_nosave() ; }
#endif
  if (time == 0) {
    //等待时间为0时,直接等待
    status = os::Solaris::cond_wait (_cond, _mutex) ;
  } else {
    //time不为0,则继续等待。
    status = os::Solaris::cond_timedwait (_cond, _mutex, &absTime);
  }
   assert_status(status == 0 || status == EINTR ||
                status == ETIME || status == ETIMEDOUT,
                status, "cond_timedwait");
#ifdef ASSERT
  thr_sigsetmask(SIG_SETMASK, &oldsigs, NULL);
#endif
  _counter = 0 ;
  status = os::Solaris::mutex_unlock(_mutex);
  assert_status(status == 0, status, "mutex_unlock") ;
  if (jt->handle_special_suspend_equivalent_condition()) {
    jt->java_suspend_self();
  }
  OrderAccess::fence();
}
void Parker::unpark() {
//定义两个变量,staus用于判断是否获取锁
  int s, status ;
  //获取锁
  status = os::Solaris::mutex_lock (_mutex) ;
  //判断是否成功
  assert (status == 0, "invariant") ;
  //存储原先变量_counter
  s = _counter;
  //把_counter设为1
  _counter = 1;
  //释放锁
  status = os::Solaris::mutex_unlock (_mutex) ;
  assert (status == 0, "invariant") ;
  if (s < 1) {
  //如果原先_counter信号量小于1,即为0,则进行signal操作,唤醒操作
    status = os::Solaris::cond_signal (_cond) ;
    assert (status == 0, "invariant") ;
  }
}

参考地址

转载于:https://my.oschina.net/cqqcqqok/blog/2049659

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值