JUC源码笔记

本文深入探讨了Java并发编程的精华部分,包括Atomic类的内部实现,如Unsafe的应用,以及各种类型的更新器。此外,还讨论了锁机制如Synchronizer和Condition监听器,以及LockSupport。文章还触及了阻塞队列的特点,特别指出ConcurrentLinkedDeque和ConcurrentLinkedQueue不支持阻塞等待操作。最后,文章分析了同步工具类、相关数据结构,并简要介绍了Future和Executor框架,特别是Executors的使用。
摘要由CSDN通过智能技术生成

Atomic

Java魔法类:Unsafe应用解析

  • 包装类型
类型 @since 关键字段 父类
AtomicBoolean 1.5 private volatile int value;
private static final long valueOffset;
AtomicInteger 1.5 private volatile int value;
private static final long valueOffset;
abstract class Number
AtomicLong 1.5 private volatile long value;
private static final long valueOffset;
static final boolean VM_SUPPORTS_LONG_CAS = VMSupportsCS8(); //底层JVM是否支持CAS
abstract class Number
  • 包装类型数组
类型 @since 关键字段 父类
AtomicIntegerArray 1.5 private final int[] array;
private static final int base = unsafe.arrayBaseOffset(int[].class);
private static final int shift = 31 - Integer.numberOfLeadingZeros(unsafe.arrayIndexScale(int[].class));
AtomicLongArray 1.5 private final long[] array;
private static final int base = unsafe.arrayBaseOffset(long[].class);
private static final int shift = 31 - Integer.numberOfLeadingZeros(unsafe.arrayIndexScale(long[].class));
  • 引用类型
类型 @since 关键字段 备注
AtomicReference 1.5 private volatile V value;
private static final long valueOffset;
AtomicReferenceArray 1.5 private final Object[] array;
private static final long arrayFieldOffset = unsafe.objectFieldOffset(AtomicReferenceArray.class.getDeclaredField(“array”));
private static final int base = unsafe.arrayBaseOffset(Object[].class);
private static final int shift= 31 - Integer.numberOfLeadingZeros(unsafe.arrayIndexScale(Object[].class));
AtomicMarkableReference 1.5 private volatile Pair pair;
private static final long pairOffset = objectFieldOffset(UNSAFE, “pair”, AtomicMarkableReference.class);
使用boolean mark来标记reference是否被修改过
AtomicStampedReference 1.5 private volatile Pair pair;
private static final long pairOffset = objectFieldOffset(UNSAFE, “pair”, AtomicStampedReference.class);
使用int stamp来标记reference是否被修改过
  • field updater
类型 @since 关键字段 备注
AtomicIntegerFieldUpdater 1.5 private final long offset;
private final Class<?> cclass;
private final Class tclass;
内部实现类AtomicIntegerFieldUpdaterImpl
AtomicLongFieldUpdater 1.5 private final long offset;
private final Class<?> cclass;
private final Class tclass;
内部实现类CASUpdater(底层CAS)、LockedUpdater
AtomicReferenceFieldUpdater 1.5 private final long offset;
private final Class<?> cclass;
private final Class tclass;
/** class holding the field /
/
* field value type */
private final Class vclass;
内部实现类AtomicReferenceFieldUpdaterImpl
  • 累加器
类型 @since 关键字段 父类
Striped64 // size is a power of 2.
transient volatile Cell[] cells;
transient volatile long base;
// Spinlock (locked via CAS) used when resizing and/or creating Cells.
transient volatile int cellsBusy;
Number
LongAccumulator 1.8 private final LongBinaryOperator function;
private final long identity;
Striped64
LongAdder 1.8 Striped64
DoubleAccumulator 1.8 private final DoubleBinaryOperator function;
private final long identity;
Striped64
DoubleAdder 1.8 Striped64

Striped64中两个重要方法:

// 处理涉及初始化、扩容、cell初始化、竞争的情况
final void longAccumulate(long x, LongBinaryOperator fn, boolean wasUncontended)
final void doubleAccumulate(double x, DoubleBinaryOperator fn, boolean wasUncontended)

Adder是Accumulater的特殊情况–累加运算,Accumulater可自定义运算。

DoubleXXX基于LongXXX的区别在于,内部会将Double转换成Long,其余一样。

相较于AtomicXXX,使用了“热点分离”的思想,用空间换时间,减少了并发冲突。

locks

  • 同步器Synchronizer
类/接口 版本 主要字段 主要方法 父类 备注
AbstractOwnableSynchronizer 1.6 /** The current owner of exclusive mode synchronization. */
private transient Thread exclusiveOwnerThread;
get/setExclusiveOwnerThread
AbstractQueuedSynchronizer 1.5 private transient volatile Node head;
private transient volatile Node tail;
/** The synchronization state. */
private volatile int state;
// 独占式获取同步状态
boolean tryAcquire(int arg)
// 独占式释放同步状态
boolean tryRelease(int arg)
// 共享式获取同步状态
int tryAcquireShared(int arg)
// 共享式私房同步状态
boolean tryReleaseShared(int arg)
// 检测当前线程是否获取独占锁
boolean isHeldExclusively()
// ----------------------------
acquireXXX/releaseXXX
AbstractOwnableSynchronizer 模板方法,子类根据需要实现独占/共享获取和释放状态。入口方法是acquireXXX和releaseXXX方法。
AbstractQueuedLongSynchronizer 1.6 private transient volatile Node head;
private transient volatile Node tail;
private volatile long state;
同上 AbstractOwnableSynchronizer
  • Condition监听器
类/接口 版本 主要字段 主要方法 父类 备注
Condition 1.5 await XXX
signal/signalAll
ConditionObject private transient Node firstWaiter;
private transient Node lastWaiter;
Condition AbstractQueuedSynchronizer、AbstractQueuedLongSynchronizer内部类。
  • LockSupport
类/接口 版本 主要字段 主要方法 父类 备注
LockSupport public static void unpark(Thread thread)
public static void park XXX
内部调用unsafe.park和unsafe.unpark方法
  • Lock
类/接口 版本 主要字段 主要方法 父类 备注
Lock 1.5 lock XXX
void unlock();
Condition newCondition();
ReadWriteLock 1.5 Lock readLock();
Lock writeLock();
ReentrantLock 1.5 private final Sync sync; Lock 内部自定义AQS实现类,分为公平锁和非公平锁。实现AQS的tryAcquire/tryRelease方法组
ReentrantReadWriteLock 1.5 private final ReentrantReadWriteLock.ReadLock readerLock;
private final ReentrantReadWriteLock.WriteLock writerLock;
final Sync sync;
public int getReadLockCount()
public boolean isWriteLocked()
public boolean isWriteLockedByCurrentThread()
public int getWriteHoldCount()
public int getReadHoldCount()
ReadWriteLock 采用读写分离的策略,允许多个线程可以同时获取读锁,满足写少读多的场景。Sync实现AQS的独占、共享模板方法。通过readLock和writeLock获取不同的锁调用对应方法。其中state标识分为两个short,高16位位读锁计数,低16位为写锁计数
https://cloud.tencent.com/developer/article/1469555
StampedLock 1.8 /** Head of CLH queue / private transient volatile WNode whead; /* Tail (last) of CLH queue / private transient volatile WNode wtail; // views transient ReadLockView readLockView; transient WriteLockView writeLockView; transient ReadWriteLockView readWriteLockView; /* Lock sequence/state / private transient volatile long state; /* extra reader count when state read count saturated */ private transient int readerOverflow; public long writeLock()
public long tryWriteLock()
public long readLock()
public long tryReadLock()
public long tryOptimisticRead()
public boolean validate(long stamp)
public void unlockWrite(long stamp)
public void unlockRead(long stamp)
public void unlock(long stamp)
public long tryConvertToWriteLock(long stamp)
public long tryConvertToReadLock(long stamp)
public long tryConvertToOptimisticRead(long stamp)
public boolean tryUnlockRead()
public boolean tryUnlockWrite()
private long cancelWaiter(WNode node, WNode group, boolean interrupted)
private long acquireRead(boolean interruptible, long deadline)
private long acquireWrite(boolean interruptible, long deadline)
对读写锁ReentrantReadWriteLock的增强,该类提供了一些功能,优化了读锁、写锁的访问,同时使读写锁之间可以互相转换,更细粒度控制并发。
StampedLockd的内部实现是基于CLH锁的(锁维护着一个等待线程队列,所有申请锁且失败的线程都记录在队列。一个节点代表一个线程)。
写锁被占用的标志是第8位为1,读锁使用0-7位,正常情况下读锁数目为1-126,超过126时,使用一个名为readerOverflow的int整型保存超出数。同时高56为用于版本校验(validate方法)
https://cloud.tencent.com/developer/article/1470988

阻塞队列

在这里插入图片描述

类/接口 版本 主要字段 主要方法 父类 备注
Queu
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值