• 锁的分类以及相关讲解


    1.锁的分类

    • 自旋锁: 线程状态及上下文切换消耗系统资源,当访问共享资源的时间短,频繁上下文切换不值得。jvm实

      现,使线程在没获得锁的时候,不被挂起,转而执行空循环,循环几次之后,如果还没能获得锁,则被挂起

    • 阻塞锁:阻塞锁改变了线程的运行状态,让线程进入阻塞状态进行等待,当获得相应的信号(唤醒或者时间)
      时,才可以进入线程的准备就绪状态,转为就绪状态的所有线程,通过竞争,进入运行状态

    • 重入锁:支持线程再次进入的锁,就跟我们有房间钥匙,可以多次进入房间类似

    • 读写锁: 两把锁,读锁跟写锁,写写互斥、读写互斥、读读共享

    • 互斥锁: 上厕所,进门之后就把门关了,不让其他人进来

    • 悲观锁: 总是假设最坏的情况,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上

      锁,这样别人想拿这个数据就会阻塞直到它拿到锁

    • 乐观锁:每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别

      人有没有去更新这个数据,可以使用版本号等机制。

    • 公平锁:大家都老老实实排队,对大家而言都很公平

    • 非公平锁:一部分人排着队,但是新来的可能插队

    • 偏向锁:偏向锁使用了一种等到竞争出现才释放锁的机制,所以当其他线程尝试竞争偏向锁时,持有偏向锁的

      线程才会释放锁

    • 独占锁:独占锁模式下,每次只能有一个线程能持有锁

    • 共享锁:允许多个线程同时获取锁,并发访问共享资源

    2.深入理解Lock接口

    Lock的使用
    lock与synchronized的区别
    lock 获取锁与释放锁的过程,都需要程序员手动的控制 Lock用的是乐观锁方式。

    所谓乐观锁就是,每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止。乐观锁实现的机制就 是CAS操作

    ​ synchronized托管给jvm执行 原始采用的是CPU悲观锁机制,即线程获得的是独占锁。独占锁意味着其他线程只能依靠阻塞来等待线程释放锁。
    实现了lock接口的锁 各个方法的简介

    /**
     * 使用Lock
     */
    public class LockDemo {
    
        //这个只能保证可见性 并不能保证原子性
        private static  int num = 0;
        private static CountDownLatch countDownLatch =new CountDownLatch(10);
    
        private static Lock lock = new ReentrantLock();
    
        /**
         * 每次调用对num进行++的操作
         *
         */
        public static  void  increment(){
            lock.lock();
            num++;
            lock.unlock();
        }
    
        public static void main(String[] args) {
    
            for (int i = 0; i < 10; i++) {
                new Thread(()->{
                    for (int j = 0; j <100 ; j++) {
                        increment();
                        try {
                            Thread.sleep(10L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                    //在每个线程只想完后调用cutdown
                    countDownLatch.countDown();
                }).start();
    
            }
    
    
            while (true){
                if(countDownLatch.getCount()==0){
                    break;
                }
            }
    
            System.out.println(num);
        }
    }
    

    3.实现属于自己的锁

    实现lock接口
    使用wait notify

    4.AbstractQueuedSynchronizer浅析

    ​ AbstractQueuedSynchronizer -- 为实现依赖于先进先出 (FIFO) 等待队列的阻塞锁和相关同步器(信号量、事件,等等)提供一个框架。

    此类的设计目标是成为依靠单个原子 int 值来表示状态的大多数同步器的一个有用基础。
    
    子类必须定义更改此状态的受保护方法,并定义哪种状态对于此对象意味着被获取或被释放。
    

    ​ 假定这些条件之后,此类中的其他方法就可以实现所有排队和阻塞机制。

    ​ 子类可以维护其他状态字段,但只是为了获得同步而只追踪使用getState()、setState(int) 和compareAndSetState(int, int) 方法来操作以原子方式更新的 int 值。

    应该将子类定义为非公共内部帮助器类,可用它们来实现其封闭类的同步属性。类 AbstractQueuedSynchronizer 没有实现任何同步接口。

    ​ 而是定义了诸如 acquireInterruptibly(int) 之类的一些方法,在适当的时候可以通过具体的锁和相关同步器来调用它们,以实现其公共方法。

    ​ 此类支持默认的独占 模式和共享 模式之一,或者二者都支持。处于独占模式下时,其他线程试图获取该锁将无法取得成功。在共享模式下,多个线程获取某个锁可能(但不是一定)会获得成功。此类并不“了解”这些不同,除了机械地意识到当在共享模式下成功获取某一锁时,下一个等待线程(如果存在)也必须确定自己是否可以成功获取该锁。
    处于不同模式下的等待线程可以共享相同的 FIFO 队列。通常,实现子类只支持其中一种模式,但两种模式都可以在(例如)ReadWriteLock 中发挥作用。只支持独占模式或者只支持共享模式的子类不必定义支持未使用模式的方法。
    此类通过支持独占模式的子类定义了一个嵌套的 AbstractQueuedSynchronizer.ConditionObject 类,可以将这个类用作 Condition 实现。isHeldExclusively() 方法将报告同步对于当前线程是否是独占的;使用当前 getState() 值调用release(int) 方法则可以完全释放此对象;如果给定保存的状态值,那么 acquire(int) 方法可以将此对象最终恢复为它以前获取的状态。

    ​ 没有别的 AbstractQueuedSynchronizer 方法创建这样的条件,因此,如果无法满足此约束,则不要使用它。AbstractQueuedSynchronizer.ConditionObject 的行为当然取决于其同步器实现的语义。此类为内部队列提供了检查、检测和监视方法,还为 condition 对象提供了类似方法。可以根据需要使用用于其同步
    机制的 AbstractQueuedSynchronizer 将这些方法导出到类中。
    此类的序列化只存储维护状态的基础原子整数,因此已序列化的对象拥有空的线程队列。需要可序列化的典型子类将定义一个 readObject 方法,该方法在反序列化时将此对象恢复到某个已知初始状态。
    tryAcquire(int)
    tryRelease(int)
    tryAcquireShared(int)
    tryReleaseShared(int)
    isHeldExclusively()
    Acquire:
      while (!tryAcquire(arg)) {
        enqueue thread if it is not already queued;
        possibly block current thread;
      }
    Release:
     if ((arg))
        unblock the first queued thread;

    5.深入剖析ReentrantLock源码之非公平锁的实现

    如何阅读源码? 一段简单的代码 看构造 看类之间的关系,形成关系图 看使用到的方法,并逐步理解,边看
    代码边看注释 debug

    6.深入剖析ReentrantLock源码之公平锁的实现

    6.1公平锁与非公平锁的区别

    公平锁:顾名思义--公平,大家老老实实排队

    非公平锁:只要有机会,就先尝试抢占资源 公平锁与非公平锁
    其实有点像在公厕上厕所。公平锁遵守排队的规则,只要前面有人在排队,那么刚进来的就老老实实排队。而
    非公平锁就有点流氓,只要当前茅坑没人,它就占了那个茅坑,不管后面的人排了多久。

    6.2源码解析
    /*
     * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     * Written by Doug Lea with assistance from members of JCP JSR-166
     * Expert Group and released to the public domain, as explained at
     * http://creativecommons.org/publicdomain/zero/1.0/
     */
    
    package java.util.concurrent.locks;
    import java.util.concurrent.TimeUnit;
    import java.util.Collection;
    
    /**
     * A reentrant mutual exclusion {@link Lock} with the same basic
     * behavior and semantics as the implicit monitor lock accessed using
     * {@code synchronized} methods and statements, but with extended
     * capabilities.
     *
     * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
     * successfully locking, but not yet unlocking it. A thread invoking
     * {@code lock} will return, successfully acquiring the lock, when
     * the lock is not owned by another thread. The method will return
     * immediately if the current thread already owns the lock. This can
     * be checked using methods {@link #isHeldByCurrentThread}, and {@link
     * #getHoldCount}.
     *
     * <p>The constructor for this class accepts an optional
     * <em>fairness</em> parameter.  When set {@code true}, under
     * contention, locks favor granting access to the longest-waiting
     * thread.  Otherwise this lock does not guarantee any particular
     * access order.  Programs using fair locks accessed by many threads
     * may display lower overall throughput (i.e., are slower; often much
     * slower) than those using the default setting, but have smaller
     * variances in times to obtain locks and guarantee lack of
     * starvation. Note however, that fairness of locks does not guarantee
     * fairness of thread scheduling. Thus, one of many threads using a
     * fair lock may obtain it multiple times in succession while other
     * active threads are not progressing and not currently holding the
     * lock.
     * Also note that the untimed {@link #tryLock()} method does not
     * honor the fairness setting. It will succeed if the lock
     * is available even if other threads are waiting.
     *
     * <p>It is recommended practice to <em>always</em> immediately
     * follow a call to {@code lock} with a {@code try} block, most
     * typically in a before/after construction such as:
     *
     *  <pre> {@code
     * class X {
     *   private final ReentrantLock lock = new ReentrantLock();
     *   // ...
     *
     *   public void m() {
     *     lock.lock();  // block until condition holds
     *     try {
     *       // ... method body
     *     } finally {
     *       lock.unlock()
     *     }
     *   }
     * }}</pre>
     *
     * <p>In addition to implementing the {@link Lock} interface, this
     * class defines a number of {@code public} and {@code protected}
     * methods for inspecting the state of the lock.  Some of these
     * methods are only useful for instrumentation and monitoring.
     *
     * <p>Serialization of this class behaves in the same way as built-in
     * locks: a deserialized lock is in the unlocked state, regardless of
     * its state when serialized.
     *
     * <p>This lock supports a maximum of 2147483647 recursive locks by
     * the same thread. Attempts to exceed this limit result in
     * {@link Error} throws from locking methods.
     *
     * @since 1.5
     * @author Doug Lea
     */
    public class ReentrantLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = 7373984872572414699L;
        /** Synchronizer providing all implementation mechanics */
        private final Sync sync;
    
        /**
         * Base of synchronization control for this lock. Subclassed
         * into fair and nonfair versions below. Uses AQS state to
         * represent the number of holds on the lock.
         */
        abstract static class Sync extends AbstractQueuedSynchronizer {
            private static final long serialVersionUID = -5179523762034025860L;
    
            /**
             * Performs {@link Lock#lock}. The main reason for subclassing
             * is to allow fast path for nonfair version.
             */
            abstract void lock();
    
            /**
             * Performs non-fair tryLock.  tryAcquire is implemented in
             * subclasses, but both need nonfair try for trylock method.
             */
            final boolean nonfairTryAcquire(int acquires) {
                final Thread current = Thread.currentThread();
                int c = getState();
                if (c == 0) {
                    if (compareAndSetState(0, acquires)) {
                        setExclusiveOwnerThread(current);
                        return true;
                    }
                }
                else if (current == getExclusiveOwnerThread()) {
                    int nextc = c + acquires;
                    if (nextc < 0) // overflow
                        throw new Error("Maximum lock count exceeded");
                    setState(nextc);
                    return true;
                }
                return false;
            }
    
            protected final boolean tryRelease(int releases) {
                int c = getState() - releases;
                if (Thread.currentThread() != getExclusiveOwnerThread())
                    throw new IllegalMonitorStateException();
                boolean free = false;
                if (c == 0) {
                    free = true;
                    setExclusiveOwnerThread(null);
                }
                setState(c);
                return free;
            }
    
            protected final boolean isHeldExclusively() {
                // While we must in general read state before owner,
                // we don't need to do so to check if current thread is owner
                return getExclusiveOwnerThread() == Thread.currentThread();
            }
    
            final ConditionObject newCondition() {
                return new ConditionObject();
            }
    
            // Methods relayed from outer class
    
            final Thread getOwner() {
                return getState() == 0 ? null : getExclusiveOwnerThread();
            }
    
            final int getHoldCount() {
                return isHeldExclusively() ? getState() : 0;
            }
    
            final boolean isLocked() {
                return getState() != 0;
            }
    
            /**
             * Reconstitutes the instance from a stream (that is, deserializes it).
             */
            private void readObject(java.io.ObjectInputStream s)
                throws java.io.IOException, ClassNotFoundException {
                s.defaultReadObject();
                setState(0); // reset to unlocked state
            }
        }
    
        /**
         * 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;
            }
        }
    
        /**
         * Creates an instance of {@code ReentrantLock}.
         * This is equivalent to using {@code ReentrantLock(false)}.
         */
        public ReentrantLock() {
            sync = new NonfairSync();
        }
    
        /**
         * Creates an instance of {@code ReentrantLock} with the
         * given fairness policy.
         *
         * @param fair {@code true} if this lock should use a fair ordering policy
         */
        public ReentrantLock(boolean fair) {
            sync = fair ? new FairSync() : new NonfairSync();
        }
    
        /**
         * Acquires the lock.
         *
         * <p>Acquires the lock if it is not held by another thread and returns
         * immediately, setting the lock hold count to one.
         *
         * <p>If the current thread already holds the lock then the hold
         * count is incremented by one and the method returns immediately.
         *
         * <p>If the lock is held by another thread then the
         * current thread becomes disabled for thread scheduling
         * purposes and lies dormant until the lock has been acquired,
         * at which time the lock hold count is set to one.
         */
        public void lock() {
            sync.lock();
        }
    
        /**
         * Acquires the lock unless the current thread is
         * {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the lock if it is not held by another thread and returns
         * immediately, setting the lock hold count to one.
         *
         * <p>If the current thread already holds this lock then the hold count
         * is incremented by one and the method returns immediately.
         *
         * <p>If the lock is held by another thread then the
         * current thread becomes disabled for thread scheduling
         * purposes and lies dormant until one of two things happens:
         *
         * <ul>
         *
         * <li>The lock is acquired by the current thread; or
         *
         * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
         * current thread.
         *
         * </ul>
         *
         * <p>If the lock is acquired by the current thread then the lock hold
         * count is set to one.
         *
         * <p>If the current thread:
         *
         * <ul>
         *
         * <li>has its interrupted status set on entry to this method; or
         *
         * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
         * the lock,
         *
         * </ul>
         *
         * then {@link InterruptedException} is thrown and the current thread's
         * interrupted status is cleared.
         *
         * <p>In this implementation, as this method is an explicit
         * interruption point, preference is given to responding to the
         * interrupt over normal or reentrant acquisition of the lock.
         *
         * @throws InterruptedException if the current thread is interrupted
         */
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }
    
        /**
         * Acquires the lock only if it is not held by another thread at the time
         * of invocation.
         *
         * <p>Acquires the lock if it is not held by another thread and
         * returns immediately with the value {@code true}, setting the
         * lock hold count to one. Even when this lock has been set to use a
         * fair ordering policy, a call to {@code tryLock()} <em>will</em>
         * immediately acquire the lock if it is available, whether or not
         * other threads are currently waiting for the lock.
         * This &quot;barging&quot; behavior can be useful in certain
         * circumstances, even though it breaks fairness. If you want to honor
         * the fairness setting for this lock, then use
         * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
         * which is almost equivalent (it also detects interruption).
         *
         * <p>If the current thread already holds this lock then the hold
         * count is incremented by one and the method returns {@code true}.
         *
         * <p>If the lock is held by another thread then this method will return
         * immediately with the value {@code false}.
         *
         * @return {@code true} if the lock was free and was acquired by the
         *         current thread, or the lock was already held by the current
         *         thread; and {@code false} otherwise
         */
        public boolean tryLock() {
            return sync.nonfairTryAcquire(1);
        }
    
        /**
         * Acquires the lock if it is not held by another thread within the given
         * waiting time and the current thread has not been
         * {@linkplain Thread#interrupt interrupted}.
         *
         * <p>Acquires the lock if it is not held by another thread and returns
         * immediately with the value {@code true}, setting the lock hold count
         * to one. If this lock has been set to use a fair ordering policy then
         * an available lock <em>will not</em> be acquired if any other threads
         * are waiting for the lock. This is in contrast to the {@link #tryLock()}
         * method. If you want a timed {@code tryLock} that does permit barging on
         * a fair lock then combine the timed and un-timed forms together:
         *
         *  <pre> {@code
         * if (lock.tryLock() ||
         *     lock.tryLock(timeout, unit)) {
         *   ...
         * }}</pre>
         *
         * <p>If the current thread
         * already holds this lock then the hold count is incremented by one and
         * the method returns {@code true}.
         *
         * <p>If the lock is held by another thread then the
         * current thread becomes disabled for thread scheduling
         * purposes and lies dormant until one of three things happens:
         *
         * <ul>
         *
         * <li>The lock is acquired by the current thread; or
         *
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
         * the current thread; or
         *
         * <li>The specified waiting time elapses
         *
         * </ul>
         *
         * <p>If the lock is acquired then the value {@code true} is returned and
         * the lock hold count is set to one.
         *
         * <p>If the current thread:
         *
         * <ul>
         *
         * <li>has its interrupted status set on entry to this method; or
         *
         * <li>is {@linkplain Thread#interrupt interrupted} while
         * acquiring the lock,
         *
         * </ul>
         * then {@link InterruptedException} is thrown and the current thread's
         * interrupted status is cleared.
         *
         * <p>If the specified waiting time elapses then the value {@code false}
         * is returned.  If the time is less than or equal to zero, the method
         * will not wait at all.
         *
         * <p>In this implementation, as this method is an explicit
         * interruption point, preference is given to responding to the
         * interrupt over normal or reentrant acquisition of the lock, and
         * over reporting the elapse of the waiting time.
         *
         * @param timeout the time to wait for the lock
         * @param unit the time unit of the timeout argument
         * @return {@code true} if the lock was free and was acquired by the
         *         current thread, or the lock was already held by the current
         *         thread; and {@code false} if the waiting time elapsed before
         *         the lock could be acquired
         * @throws InterruptedException if the current thread is interrupted
         * @throws NullPointerException if the time unit is null
         */
        public boolean tryLock(long timeout, TimeUnit unit)
                throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
        }
    
        /**
         * Attempts to release this lock.
         *
         * <p>If the current thread is the holder of this lock then the hold
         * count is decremented.  If the hold count is now zero then the lock
         * is released.  If the current thread is not the holder of this
         * lock then {@link IllegalMonitorStateException} is thrown.
         *
         * @throws IllegalMonitorStateException if the current thread does not
         *         hold this lock
         */
        public void unlock() {
            sync.release(1);
        }
    
        /**
         * Returns a {@link Condition} instance for use with this
         * {@link Lock} instance.
         *
         * <p>The returned {@link Condition} instance supports the same
         * usages as do the {@link Object} monitor methods ({@link
         * Object#wait() wait}, {@link Object#notify notify}, and {@link
         * Object#notifyAll notifyAll}) when used with the built-in
         * monitor lock.
         *
         * <ul>
         *
         * <li>If this lock is not held when any of the {@link Condition}
         * {@linkplain Condition#await() waiting} or {@linkplain
         * Condition#signal signalling} methods are called, then an {@link
         * IllegalMonitorStateException} is thrown.
         *
         * <li>When the condition {@linkplain Condition#await() waiting}
         * methods are called the lock is released and, before they
         * return, the lock is reacquired and the lock hold count restored
         * to what it was when the method was called.
         *
         * <li>If a thread is {@linkplain Thread#interrupt interrupted}
         * while waiting then the wait will terminate, an {@link
         * InterruptedException} will be thrown, and the thread's
         * interrupted status will be cleared.
         *
         * <li> Waiting threads are signalled in FIFO order.
         *
         * <li>The ordering of lock reacquisition for threads returning
         * from waiting methods is the same as for threads initially
         * acquiring the lock, which is in the default case not specified,
         * but for <em>fair</em> locks favors those threads that have been
         * waiting the longest.
         *
         * </ul>
         *
         * @return the Condition object
         */
        public Condition newCondition() {
            return sync.newCondition();
        }
    
        /**
         * Queries the number of holds on this lock by the current thread.
         *
         * <p>A thread has a hold on a lock for each lock action that is not
         * matched by an unlock action.
         *
         * <p>The hold count information is typically only used for testing and
         * debugging purposes. For example, if a certain section of code should
         * not be entered with the lock already held then we can assert that
         * fact:
         *
         *  <pre> {@code
         * class X {
         *   ReentrantLock lock = new ReentrantLock();
         *   // ...
         *   public void m() {
         *     assert lock.getHoldCount() == 0;
         *     lock.lock();
         *     try {
         *       // ... method body
         *     } finally {
         *       lock.unlock();
         *     }
         *   }
         * }}</pre>
         *
         * @return the number of holds on this lock by the current thread,
         *         or zero if this lock is not held by the current thread
         */
        public int getHoldCount() {
            return sync.getHoldCount();
        }
    
        /**
         * Queries if this lock is held by the current thread.
         *
         * <p>Analogous to the {@link Thread#holdsLock(Object)} method for
         * built-in monitor locks, this method is typically used for
         * debugging and testing. For example, a method that should only be
         * called while a lock is held can assert that this is the case:
         *
         *  <pre> {@code
         * class X {
         *   ReentrantLock lock = new ReentrantLock();
         *   // ...
         *
         *   public void m() {
         *       assert lock.isHeldByCurrentThread();
         *       // ... method body
         *   }
         * }}</pre>
         *
         * <p>It can also be used to ensure that a reentrant lock is used
         * in a non-reentrant manner, for example:
         *
         *  <pre> {@code
         * class X {
         *   ReentrantLock lock = new ReentrantLock();
         *   // ...
         *
         *   public void m() {
         *       assert !lock.isHeldByCurrentThread();
         *       lock.lock();
         *       try {
         *           // ... method body
         *       } finally {
         *           lock.unlock();
         *       }
         *   }
         * }}</pre>
         *
         * @return {@code true} if current thread holds this lock and
         *         {@code false} otherwise
         */
        public boolean isHeldByCurrentThread() {
            return sync.isHeldExclusively();
        }
    
        /**
         * Queries if this lock is held by any thread. This method is
         * designed for use in monitoring of the system state,
         * not for synchronization control.
         *
         * @return {@code true} if any thread holds this lock and
         *         {@code false} otherwise
         */
        public boolean isLocked() {
            return sync.isLocked();
        }
    
        /**
         * Returns {@code true} if this lock has fairness set true.
         *
         * @return {@code true} if this lock has fairness set true
         */
        public final boolean isFair() {
            return sync instanceof FairSync;
        }
    
        /**
         * Returns the thread that currently owns this lock, or
         * {@code null} if not owned. When this method is called by a
         * thread that is not the owner, the return value reflects a
         * best-effort approximation of current lock status. For example,
         * the owner may be momentarily {@code null} even if there are
         * threads trying to acquire the lock but have not yet done so.
         * This method is designed to facilitate construction of
         * subclasses that provide more extensive lock monitoring
         * facilities.
         *
         * @return the owner, or {@code null} if not owned
         */
        protected Thread getOwner() {
            return sync.getOwner();
        }
    
        /**
         * Queries whether any threads are waiting to acquire this lock. Note that
         * because cancellations may occur at any time, a {@code true}
         * return does not guarantee that any other thread will ever
         * acquire this lock.  This method is designed primarily for use in
         * monitoring of the system state.
         *
         * @return {@code true} if there may be other threads waiting to
         *         acquire the lock
         */
        public final boolean hasQueuedThreads() {
            return sync.hasQueuedThreads();
        }
    
        /**
         * Queries whether the given thread is waiting to acquire this
         * lock. Note that because cancellations may occur at any time, a
         * {@code true} return does not guarantee that this thread
         * will ever acquire this lock.  This method is designed primarily for use
         * in monitoring of the system state.
         *
         * @param thread the thread
         * @return {@code true} if the given thread is queued waiting for this lock
         * @throws NullPointerException if the thread is null
         */
        public final boolean hasQueuedThread(Thread thread) {
            return sync.isQueued(thread);
        }
    
        /**
         * Returns an estimate of the number of threads waiting to
         * acquire this lock.  The value is only an estimate because the number of
         * threads may change dynamically while this method traverses
         * internal data structures.  This method is designed for use in
         * monitoring of the system state, not for synchronization
         * control.
         *
         * @return the estimated number of threads waiting for this lock
         */
        public final int getQueueLength() {
            return sync.getQueueLength();
        }
    
        /**
         * Returns a collection containing threads that may be waiting to
         * acquire this lock.  Because the actual set of threads may change
         * dynamically while constructing this result, the returned
         * collection is only a best-effort estimate.  The elements of the
         * returned collection are in no particular order.  This method is
         * designed to facilitate construction of subclasses that provide
         * more extensive monitoring facilities.
         *
         * @return the collection of threads
         */
        protected Collection<Thread> getQueuedThreads() {
            return sync.getQueuedThreads();
        }
    
        /**
         * Queries whether any threads are waiting on the given condition
         * associated with this lock. Note that because timeouts and
         * interrupts may occur at any time, a {@code true} return does
         * not guarantee that a future {@code signal} will awaken any
         * threads.  This method is designed primarily for use in
         * monitoring of the system state.
         *
         * @param condition the condition
         * @return {@code true} if there are any waiting threads
         * @throws IllegalMonitorStateException if this lock is not held
         * @throws IllegalArgumentException if the given condition is
         *         not associated with this lock
         * @throws NullPointerException if the condition is null
         */
        public boolean hasWaiters(Condition condition) {
            if (condition == null)
                throw new NullPointerException();
            if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
                throw new IllegalArgumentException("not owner");
            return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
        }
    
        /**
         * Returns an estimate of the number of threads waiting on the
         * given condition associated with this lock. Note that because
         * timeouts and interrupts may occur at any time, the estimate
         * serves only as an upper bound on the actual number of waiters.
         * This method is designed for use in monitoring of the system
         * state, not for synchronization control.
         *
         * @param condition the condition
         * @return the estimated number of waiting threads
         * @throws IllegalMonitorStateException if this lock is not held
         * @throws IllegalArgumentException if the given condition is
         *         not associated with this lock
         * @throws NullPointerException if the condition is null
         */
        public int getWaitQueueLength(Condition condition) {
            if (condition == null)
                throw new NullPointerException();
            if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
                throw new IllegalArgumentException("not owner");
            return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
        }
    
        /**
         * Returns a collection containing those threads that may be
         * waiting on the given condition associated with this lock.
         * Because the actual set of threads may change dynamically while
         * constructing this result, the returned collection is only a
         * best-effort estimate. The elements of the returned collection
         * are in no particular order.  This method is designed to
         * facilitate construction of subclasses that provide more
         * extensive condition monitoring facilities.
         *
         * @param condition the condition
         * @return the collection of threads
         * @throws IllegalMonitorStateException if this lock is not held
         * @throws IllegalArgumentException if the given condition is
         *         not associated with this lock
         * @throws NullPointerException if the condition is null
         */
        protected Collection<Thread> getWaitingThreads(Condition condition) {
            if (condition == null)
                throw new NullPointerException();
            if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
                throw new IllegalArgumentException("not owner");
            return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
        }
    
        /**
         * Returns a string identifying this lock, as well as its lock state.
         * The state, in brackets, includes either the String {@code "Unlocked"}
         * or the String {@code "Locked by"} followed by the
         * {@linkplain Thread#getName name} of the owning thread.
         *
         * @return a string identifying this lock, as well as its lock state
         */
        public String toString() {
            Thread o = sync.getOwner();
            return super.toString() + ((o == null) ?
                                       "[Unlocked]" :
                                       "[Locked by thread " + o.getName() + "]");
        }
    }
    
    

    非公平锁的弊端
    可能导致后面排队等待的线程等不到相应的cpu资源,从而引起线程饥饿

    7.掌控线程执行顺序之多线程debug

    8.读写锁特性及ReentrantReadWriteLock的使用

    特性:写写互斥、读写互斥、读读共享
    锁降级:写线程获取写入锁后可以获取读取锁,然后释放写入锁,这样就从写入锁变成了读取锁,从而实现锁
    降级的特性。

    9.源码探秘之AQS如何用单一int值表示读写两种状态

    10.深入剖析ReentrantReadWriteLock之读锁源码实现

    int 是32位,将其拆分成两个无符号short
    高位表示读锁     低位表示写锁
    0000000000000000  0000000000000000
    两种锁的最大次数均为65535也即是2的16次方减去1
    读锁: 每次都从当前的状态加上65536
    0000000000000000  0000000000000000

    0000000000000001  0000000000000000

    0000000000000001  0000000000000000

    0000000000000001  0000000000000000

    0000000000000010  0000000000000000
    获取读锁个数,将state整个无符号右移16位就可得出读锁的个数
     0000000000000001
    写锁:每次都直接加1
    0000000000000000  0000000000000000

    0000000000000000  0000000000000001

    0000000000000000  0000000000000001
    获取写锁的个数
    0000000000000000  0000000000000001

    0000000000000000  1111111111111111

    0000000000000000  0000000000000001

    11. 深入剖析ReentrantReadWriteLock之写锁源码实现

    0000000000000000 0000000000000001

    0000000000000000 111111111111111111
    0000000000000000 0000000000000001

    12.锁降级详解

    锁降级:写线程获取写入锁后可以获取读取锁,然后释放写入锁,这样就从写入锁变成了读取锁,从而实现锁
    降级的特性。
    注意点:锁降级之后,写锁并不会直接降级成读锁,不会随着读锁的释放而释放,因此需要显式地释放写锁

    12.1是否有锁升级?

    在ReentrantReadWriteLock里面,不存在锁升级这一说法
    锁降级的应用场景
    用于对数据比较敏感,需要在对数据修改之后,获取到修改后的值,并进行接下来的其他操作

    13.StampedLock原理及使用

    1.8之前,锁已经那么多了,为什么还要有StampedLock?
    一般应用,都是读多写少,ReentrantReadWriteLock 因读写互斥,故读时阻塞写,因而性能上上不去。可能
    会使写线程饥饿

    13.1 StampedLock的特点

    所有获取锁的方法,都返回一个邮戳(Stamp),Stamp为0表示获取失败,其余都表示成功; 所有释放锁的
    方法,都需要一个邮戳(Stamp),这个Stamp必须是和成功获取锁时得到的Stamp一致; StampedLock是
    不可重入的;(如果一个线程已经持有了写锁,再去获取写锁的话就会造成死锁) 支持锁升级跟锁降级 可
    以乐观读也可以悲观读 使用有限次自旋,增加锁获得的几率,避免上下文切换带来的开销 乐观读不阻塞写
    操作,悲观读,阻塞写得操作

    13.2 StampedLock的优点

    相比于ReentrantReadWriteLock,吞吐量大幅提升

    13.13 StampedLock的缺点

    api相对复杂,容易用错 内部实现相比于ReentrantReadWriteLock复杂得多
    StampedLock的原理
    每次获取锁的时候,都会返回一个邮戳(stamp),相当于mysql里的version字段 释放锁的时候,再根据之
    前的获得的邮戳,去进行锁释放
    使用stampedLock注意点
    如果使用乐观读,一定要判断返回的邮戳是否是一开始获得到的,如果不是,要去获取悲观读锁,再次去读取

    /**
     * StampedLock Demo
     */
    public class StampedLockDemo {
        // 成员变量
        private double x, y;
    
        // 锁实例
        private final StampedLock sl = new StampedLock();
    
        // 排它锁-写锁(writeLock)
        void move(double deltaX, double deltaY) {
            long stamp = sl.writeLock();
            try {
                x += deltaX;
                y += deltaY;
            } finally {
                sl.unlockWrite(stamp);
            }
        }
    
        // 乐观读锁
        double distanceFromOrigin() {
    
            // 尝试获取乐观读锁(1)
            long stamp = sl.tryOptimisticRead();
            // 将全部变量拷贝到方法体栈内(2)
            double currentX = x, currentY = y;
            // 检查在(1)获取到读锁票据后,锁有没被其他写线程排它性抢占(3)
            if (!sl.validate(stamp)) {
                // 如果被抢占则获取一个共享读锁(悲观获取)(4)
                stamp = sl.readLock();
                try {
                    // 将全部变量拷贝到方法体栈内(5)
                    currentX = x;
                    currentY = y;
                } finally {
                    // 释放共享读锁(6)
                    sl.unlockRead(stamp);
                }
            }
            // 返回计算结果(7)
            return Math.sqrt(currentX * currentX + currentY * currentY);
        }
    
        // 使用悲观锁获取读锁,并尝试转换为写锁
        void moveIfAtOrigin(double newX, double newY) {
            // 这里可以使用乐观读锁替换(1)
            long stamp = sl.readLock();
            try {
                // 如果当前点在原点则移动(2)
                while (x == 0.0 && y == 0.0) {
                    // 尝试将获取的读锁升级为写锁(3)
                    long ws = sl.tryConvertToWriteLock(stamp);
                    // 升级成功,则更新票据,并设置坐标值,然后退出循环(4)
                    if (ws != 0L) {
                        stamp = ws;
                        x = newX;
                        y = newY;
                        break;
                    } else {
                        // 读锁升级写锁失败则释放读锁,显示获取独占写锁,然后循环重试(5)
                        sl.unlockRead(stamp);
                        stamp = sl.writeLock();
                    }
                }
            } finally {
                // 释放锁(6)
                sl.unlock(stamp);
            }
        }
    }
    
  • 相关阅读:
    自动化测试基础
    appium环境搭建
    Typescript类型体操 Readonly
    Typescript类型体操 Tuple To Object
    Typescript类型体操 If
    Typescript类型体操 Length of Tuple
    Typescript类型体操 First of Array
    80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
    MySQL精品学习资源合集 | 含学习教程笔记、运维技巧、图书推荐
    居安思危,安全先行 | 7月《中国数据库行业分析报告》精彩概览!
  • 原文地址:https://www.cnblogs.com/charlypage/p/10886370.html
Copyright © 2020-2023  润新知