java非公平锁实例详解

1、非公平锁不能保证锁的获取是按照请求锁的顺序进行的。这可能会导致某个或某些线程永远得不到锁。

2、CPU唤醒线程的费用可以降低,整体吞吐效率会很高。但是可能会有线程长时间甚至永远得不到锁,导致饿死。

实例

/**
   * Sync object for non-fair locks
   */
  static final class NonfairSync extends Sync {
      private static final long serialVersionUID = 7316153563782823691L;

      /**
       * Performs lock.  Try immediate barge, backing up to normal
       * acquire on failure.
       */
      final void lock() {
          if (compareAndSetState(0, 1))
              setExclusiveOwnerThread(Thread.currentThread());
          else
              acquire(1);
      }

      protected final boolean tryAcquire(int acquires) {
          return nonfairTryAcquire(acquires);
      }
  }

  /**
   * Sync object for fair locks
   */
  static final class FairSync extends Sync {
      private static final long serialVersionUID = -3000897897090466540L;

      final void lock() {
          acquire(1);
      }

      /**
       * Fair version of tryAcquire.  Don't grant access unless
       * recursive call or no waiters or is first.
       */
      protected final boolean tryAcquire(int acquires) {
          final Thread current = Thread.currentThread();
          int c = getState();
          if (c == 0) {
              if (!hasQueuedPredecessors() &&
                  compareAndSetState(0, acquires)) {
                  setExclusiveOwnerThread(current);
                  return true;
              }
          }
          else if (current == getExclusiveOwnerThread()) {
              int nextc = c + acquires;
              if (nextc < 0)
                  throw new Error("Maximum lock count exceeded");
              setState(nextc);
              return true;
          }
          return false;
      }
  }

知识点扩展:

非公平锁,顾名思义,各个线程获取到锁的顺序,不一定和它们申请的先后顺序一致,有可能后来的线程,反而先获取到了锁。

在实现上,公平锁在进行lock时,首先会进行tryAcquire()操作。在tryAcquire中,会判断等待队列中是否已经有别的线程在等待了。如果队列中已经有别的线程了,则tryAcquire失败,则将自己加入队列。如果队列中没有别的线程,则进行获取锁的操作。

/**
   * Fair version of tryAcquire. Don't grant access unless
   * recursive call or no waiters or is first.
   **/
  protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) {
      if (!hasQueuedPredecessors() &&
        compareAndSetState(0, acquires)) {
        setExclusiveOwnerThread(current);
        return true;
      }
    }
    else if (current == getExclusiveOwnerThread()) {
      int nextc = c + acquires;
      if (nextc < 0)
        throw new Error("Maximum lock count exceeded");
      setState(nextc);
      return true;
    }
    return false;
  }

非公平锁,在进行lock时,会直接尝试进行加锁,如果成功,则获取到锁,如果失败,则进行和公平锁相同的动作。

关于java非公平锁知识点实例详解的文章就介绍至此,更多相关java非公平锁如何理解内容请搜索编程宝库以前的文章,希望大家多多支持编程宝库

 什么是树形结构数据 效果 用法String jsonStr = "{\"name\":\"aaa\",\"children\":[{\"name\":\"bbb\",\"c ...