找回密码
 立即注册
首页 业界区 安全 Java源码分析系列笔记-5.手写AQS

Java源码分析系列笔记-5.手写AQS

绘纵 2025-6-23 18:42:11
目录

  • 1. 需求
  • 2. 定义属性

    • 2.1. 锁的排他性
    • 2.2. 锁的状态
    • 2.3. 阻塞、唤醒线程
    • 2.4. 使用队列保存抢占锁失败的线程

  • 3. 添加加锁、解锁操作

    • 3.1. 基本流程
    • 3.2. 唤醒后继续抢占锁
    • 3.3. 加入公平锁的特性

  • 4. 最终定版
  • 5. 测试
  • 6. 流程

我们可以自己动手写一个简单的AQS,以更好地理解AQS实际的源码
1. 需求


  • 锁是排他的,一旦这个锁被某个线程占有,只要这个锁没被释放,他就不能被其他线程占有。因此需要保存当前占有锁的线程
  • 要有一个单独的字段表示当前锁的状态,是空闲还是已被占有
  • 同一时间有很多线程抢占锁,只有一个线程能成功,那其他线程怎么办呢?
    一是要让其他线程暂时停止抢占锁,即阻塞这些线程;既然有了阻塞,那必然有唤醒操作,占有锁的线程在释放锁的同时需要唤醒其他阻塞等待锁的线程
  • 另外需要用一个队列保存抢占锁失败的线程以便后续唤醒继续抢占锁,注意这个队列的操作得是线程安全的。
2. 定义属性

2.1. 锁的排他性

1.考虑用一个字段Thread lockHolder表示当前占有锁的线程,在多线程情况下为了保证这个变量改动后能及时被其他线程感知,使用volatile修饰
  1. public class MyLock
  2. {
  3.     //表示当前持有锁的线程
  4.     private volatile Thread lockHolder;
  5. }
复制代码
2.2. 锁的状态


  • 使用int state表示锁的状态,0表示空闲未被占有,1表示已被占有,对他的操作必须保证是原子的,使用CAS;同样在多线程情况下为了保证这个变量改动后能及时被其他线程感知,使用volatile修饰
  1. public class MyLock
  2. {
  3.     //表示加锁状态。记录加锁的次数
  4.     private volatile int state = 0;
  5.     //...
  6. }
复制代码
Java中使用CAS操作需要一个Unsafe类的实例,如下:
  1. public class MyLock
  2. {
  3.     //...
  4.    
  5.     private static final Unsafe unsafe = UnsafeInstance.getInstance();
  6.     //state变量的偏移地址。通过unsafe实现CAS操作的时候需要用到
  7.     private static final long stateOffset;
  8.     static
  9.     {
  10.         try
  11.         {
  12.             stateOffset = unsafe.objectFieldOffset(MyLock.class.getDeclaredField("state"));
  13.         }catch (Exception e)
  14.         {
  15.             throw new Error();
  16.         }
  17.     }
  18.     //CAS操作设置state
  19.     public final boolean compareAndSwapState(int except, int update)
  20.     {
  21.         return unsafe.compareAndSwapInt(this, stateOffset, except, update);
  22.     }
  23.     //通过反射的方式获取Unsafe实例
  24.     private static class UnsafeInstance
  25.     {
  26.         public static Unsafe getInstance()
  27.         {
  28.             try
  29.             {
  30.                 Field field = Unsafe.class.getDeclaredField("theUnsafe");
  31.                 field.setAccessible(true);
  32.                 return (Unsafe) field.get(null);
  33.             }
  34.             catch (Exception e)
  35.             {
  36.                 e.printStackTrace();
  37.             }
  38.             return null;
  39.         }
  40.     }
  41. }
复制代码
2.3. 阻塞、唤醒线程


  • 使用LockSupport.unpark阻塞线程,使用LockSupport.park唤醒线程
2.4. 使用队列保存抢占锁失败的线程


  • 线程安全的queue考虑使用ConcurrentLinkedQueue,如下
  1. public class MyLock
  2. {
  3.     //保存未获取的线程
  4.     private ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<>();
  5.     //...
  6. }
复制代码

  • 整理上述代码
  1. public class MyLock
  2. {
  3.     //表示加锁状态。记录加锁的次数
  4.     private volatile int state = 0;
  5.     //表示当前持有锁的线程
  6.     private volatile Thread lockHolder;
  7.     //保存未获取的线程
  8.     private ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<>();
  9.     //==================UNSAFE======================//
  10.     private static final Unsafe unsafe = UnsafeInstance.getInstance();
  11.     //state变量的偏移地址。通过unsafe实现CAS操作的时候需要用到
  12.     private static final long stateOffset;
  13.     static
  14.     {
  15.         try
  16.         {
  17.             stateOffset = unsafe.objectFieldOffset(MyLock.class.getDeclaredField("state"));
  18.         }catch (Exception e)
  19.         {
  20.             throw new Error();
  21.         }
  22.     }
  23.     //CAS操作设置state
  24.     public final boolean compareAndSwapState(int except, int update)
  25.     {
  26.         return unsafe.compareAndSwapInt(this, stateOffset, except, update);
  27.     }
  28.     //通过反射的方式获取Unsafe实例
  29.     private static class UnsafeInstance
  30.     {
  31.         public static Unsafe getInstance()
  32.         {
  33.             try
  34.             {
  35.                 Field field = Unsafe.class.getDeclaredField("theUnsafe");
  36.                 field.setAccessible(true);
  37.                 return (Unsafe) field.get(null);
  38.             }
  39.             catch (Exception e)
  40.             {
  41.                 e.printStackTrace();
  42.             }
  43.             return null;
  44.         }
  45.     }  
复制代码
3. 添加加锁、解锁操作

3.1. 基本流程

伪代码如下:

  • 检查锁的状态
  • 如果没有线程占用锁那么尝试抢占锁(CAS原子操作)
  • 抢占成功设置当前占有锁的线程
  • 抢占失败入队阻塞
  1. //加锁的操作
  2. public void lock()
  3. {
  4.     Thread currentThread = Thread.currentThread();
  5.     int state = getState();
  6.     //state==0表示没有加锁
  7.     if (state == 0)
  8.     {
  9.         //CAS设置成功即加锁成功
  10.         if (compareAndSwapState(0, 1))
  11.         {
  12.             setLockHolder(currentThread);//设置当前持有锁的线程
  13.             return;
  14.         }
  15.     }
  16.    
  17.     //获取锁失败,入队
  18.     waiters.add(currentThread);
  19.     //获取锁失败阻塞当前线程
  20.     LockSupport.park(currentThread);//由unpark唤醒
  21.    
  22. }
复制代码

  • 解锁
    伪代码如下:
  • 解锁的线程(即当前线程)必须是占有锁的线程
  • 是的话使用CAS解锁
  • 解锁成功则置当前占有锁的线程为空,必须唤醒阻塞的线程
  1. public void unlock()
  2. {
  3.     //加锁和解锁的线程必须相同
  4.     if (Thread.currentThread() != lockHolder)
  5.     {
  6.         throw new RuntimeException("current thread is not lockHolder");
  7.     }
  8.     //CAS设置state成功,解锁
  9.     int state = getState();
  10.     if (compareAndSwapState(state, 0))
  11.     {
  12.         setLockHolder(null);
  13.         //唤醒等待锁的所有线程
  14.         for (Thread waiter : waiters)
  15.         {
  16.            LockSupport.unpark(head);//唤醒park
  17.         }
  18.         
  19.     }
  20. }
复制代码
3.2. 唤醒后继续抢占锁

上面的加锁代码被唤醒后需要再次尝试获取锁,如果失败则阻塞;被唤醒后再次尝试获取锁.....
直到成功设置当前线程为占有锁的线程,并且把当前线程从等待队列中移除
可以看出这是一个死循环,修改加锁代码如下:
  1. public void lock()
  2. {
  3.     //加锁成功
  4.     if (acquire())
  5.     {
  6.         return;
  7.     }
  8.     //获取锁失败,入队
  9.     Thread currentThread = Thread.currentThread();
  10.     waiters.add(currentThread);
  11.     for (;;)
  12.     {
  13.         //不停的尝试获取锁
  14.         if (acquire())
  15.         {
  16.             return;
  17.         }
  18.         //获取锁失败阻塞当前线程
  19.         LockSupport.park(currentThread);//由unpark唤醒
  20.     }
  21. }
  22. private boolean acquire()
  23. {
  24.     Thread currentThread = Thread.currentThread();
  25.     int state = getState();
  26.     //state==0表示没有加锁
  27.     if (state == 0)
  28.     {
  29.         //CAS设置成功即加锁成功
  30.         if (compareAndSwapState(0, 1))
  31.         {
  32.             waiters.remove(Thread.currentThread());//拿到锁了从等待队列中移除
  33.             setLockHolder(currentThread);//设置当前持有锁的线程
  34.             return true;
  35.         }
  36.     }
  37.     return false;
  38. }
复制代码
3.3. 加入公平锁的特性

所谓公平锁就是遵循先到先得的原则。加锁失败的线程会放入队列中进而阻塞,当占有锁的线程释放锁成功后应该唤醒等待时间最长的线程(队头),让他去尝试抢占锁。
修改代码如下:
  1. public void lock()
  2. {
  3.     //加锁成功
  4.     if (acquire())
  5.     {
  6.         return;
  7.     }
  8.     //获取锁失败,入队
  9.     Thread currentThread = Thread.currentThread();
  10.     waiters.add(currentThread);
  11.     for (;;)
  12.     {
  13.         //队列中为空(没有人等待)或者是队头(我才是第一个等待)才能去获取锁这才公平
  14.         //不停的尝试获取锁
  15.         if ((waiters.isEmpty() || currentThread == waiters.peek()) && acquire())
  16.         {
  17.             return;
  18.         }
  19.         //获取锁失败阻塞当前线程
  20.         LockSupport.park(currentThread);//由unpark唤醒
  21.     }
  22. }
  23. private boolean acquire()
  24. {
  25.     Thread currentThread = Thread.currentThread();
  26.     int state = getState();
  27.     //state==0表示没有加锁
  28.     if (state == 0)
  29.     {
  30.         //队列为空(即前面没人等待锁我才去尝试加锁,这样才公平)
  31.         //又或者当前线程就是队头才去尝试加锁
  32.         //CAS设置成功即加锁成功
  33.         if ((waiters.isEmpty() || currentThread == waiters.peek()) && compareAndSwapState(0, 1))
  34.         {
  35.             waiters.poll();//拿到锁了从等待队列中移除
  36.             setLockHolder(currentThread);//设置当前持有锁的线程
  37.             return true;
  38.         }
  39.     }
  40.     return false;
  41. }
  42. public void unlock()
  43. {
  44.     //加锁和解锁的线程必须相同
  45.     if (Thread.currentThread() != lockHolder)
  46.     {
  47.         throw new RuntimeException("current thread is not lockHolder");
  48.     }
  49.     //CAS设置state成功,解锁
  50.     int state = getState();
  51.     if (compareAndSwapState(state, 0))
  52.     {
  53.         setLockHolder(null);
  54.         //唤醒等待锁的队头线程
  55.         Thread head = waiters.peek();
  56.         if (head != null)
  57.         {
  58.             LockSupport.unpark(head);//唤醒park
  59.         }
  60.     }
  61. }
复制代码
4. 最终定版
  1. public class MyLock
  2. {
  3.     //表示加锁状态。记录加锁的次数
  4.     private volatile int state = 0;
  5.     //表示当前持有锁的线程
  6.     private volatile Thread lockHolder;
  7.     //保存未获取的线程
  8.     private ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<>();
  9.     public void lock()
  10.     {
  11.         //加锁成功
  12.         if (acquire())
  13.         {
  14.             return;
  15.         }
  16.         //获取锁失败,入队
  17.         Thread currentThread = Thread.currentThread();
  18.         waiters.add(currentThread);
  19.         for (;;)
  20.         {
  21.             //队列中为空(没有人等待)或者是队头(我才是第一个等待)才能去获取锁这才公平
  22.             //不停的尝试获取锁
  23.             if ((waiters.isEmpty() || currentThread == waiters.peek()) && acquire())
  24.             {
  25.                 return;
  26.             }
  27.             //获取锁失败阻塞当前线程
  28.             LockSupport.park(currentThread);//由unpark唤醒
  29.         }
  30.     }
  31.     private boolean acquire()
  32.     {
  33.         Thread currentThread = Thread.currentThread();
  34.         int state = getState();
  35.         //state==0表示没有加锁
  36.         if (state == 0)
  37.         {
  38.             //队列为空(即前面没人等待锁我才去尝试加锁,这样才公平)
  39.             //又或者当前线程就是队头才去尝试加锁
  40.             //CAS设置成功即加锁成功
  41.             if ((waiters.isEmpty() || currentThread == waiters.peek()) && compareAndSwapState(0, 1))
  42.             {
  43.                 waiters.poll();//拿到锁了从等待队列中移除
  44.                 setLockHolder(currentThread);//设置当前持有锁的线程
  45.                 return true;
  46.             }
  47.         }
  48.         return false;
  49.     }
  50.     public void unlock()
  51.     {
  52.         //加锁和解锁的线程必须相同
  53.         if (Thread.currentThread() != lockHolder)
  54.         {
  55.             throw new RuntimeException("current thread is not lockHolder");
  56.         }
  57.         //CAS设置state成功,解锁
  58.         int state = getState();
  59.         if (compareAndSwapState(state, 0))
  60.         {
  61.             setLockHolder(null);
  62.             //唤醒等待锁的队头线程
  63.             Thread head = waiters.peek();
  64.             if (head != null)
  65.             {
  66.                 LockSupport.unpark(head);//唤醒park
  67.             }
  68.         }
  69.     }
  70.     public int getState()
  71.     {
  72.         return state;
  73.     }
  74.     public void setState(int state)
  75.     {
  76.         this.state = state;
  77.     }
  78.     public Thread getLockHolder()
  79.     {
  80.         return lockHolder;
  81.     }
  82.     public void setLockHolder(Thread lockHolder)
  83.     {
  84.         this.lockHolder = lockHolder;
  85.     }
  86.     //==================UNSAFE======================//
  87.     private static final Unsafe unsafe = UnsafeInstance.getInstance();
  88.     //state变量的偏移地址。通过unsafe实现CAS操作的时候需要用到
  89.     private static final long stateOffset;
  90.     static
  91.     {
  92.         try
  93.         {
  94.             stateOffset = unsafe.objectFieldOffset(MyLock.class.getDeclaredField("state"));
  95.         }catch (Exception e)
  96.         {
  97.             throw new Error();
  98.         }
  99.     }
  100.     //CAS操作设置state
  101.     public final boolean compareAndSwapState(int except, int update)
  102.     {
  103.         return unsafe.compareAndSwapInt(this, stateOffset, except, update);
  104.     }
  105.     //通过反射的方式获取Unsafe实例
  106.     private static class UnsafeInstance
  107.     {
  108.         public static Unsafe getInstance()
  109.         {
  110.             try
  111.             {
  112.                 Field field = Unsafe.class.getDeclaredField("theUnsafe");
  113.                 field.setAccessible(true);
  114.                 return (Unsafe) field.get(null);
  115.             }
  116.             catch (Exception e)
  117.             {
  118.                 e.printStackTrace();
  119.             }
  120.             return null;
  121.         }
  122.     }
  123.    
  124. }
复制代码
5. 测试
  1. private static int result = 0;
  2. public static void main(String[] args) throws InterruptedException
  3. {
  4.     final int threadCound = 10000;
  5.     final CyclicBarrier barrier = new CyclicBarrier(threadCound);
  6.     final CountDownLatch countDownLatch = new CountDownLatch(threadCound);
  7.     final MyLock lock = new MyLock();
  8.     for (int i = 0; i < threadCound; i++)
  9.     {
  10.         String name = "thread-" + i;
  11.         new Thread(()->{
  12.             try
  13.             {
  14.                 barrier.await();
  15.                 lock.lock();
  16.                 result++;
  17.                 System.out.println(Thread.currentThread() + " result: " + result);
  18.             }
  19.             catch (Exception e)
  20.             {
  21.                 e.printStackTrace();
  22.             }
  23.             finally
  24.             {
  25.                 lock.unlock();
  26.                 countDownLatch.countDown();
  27.             }
  28.         }, name).start();
  29.     }
  30.     countDownLatch.await();
  31.     System.out.println(result);
  32. }
复制代码
6. 流程

1.png


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册