一、StampedLock
该类从JDK1.8 加入,是为了进一步优化读性能,它的特点是在使用读锁、写锁时必须配合【戳】使用。
加解读锁
long stamp = lock.readLock();
lock.unlockRead(stamp);
加解写锁
long stamp = lock.writeLock();
lock.unlockWrite(stamp);
乐观读,StampedLock 支持 tryOptimisticRead()方法(乐观读),读取完毕后需要做一次戳校验,如果校验通过,表示这期间确实没有写操作,数据可以安全使用,如果校验没通过,则需要重新获取读锁,保证数据安全。
long stamp = lock.tryOptimisticRead();
// 验戳
if(!lock.validate(stamp)){
// 锁升级
}
例:
class DataContainerStamped{
private int data;
private final StampedLock lock = new StampedLock();
public DataContainerStamped(int data) {
this.data = data;
}
public int read(int readTime){
long stamp = lock.tryOptimisticRead();
//读
// 乐观读
if(lock.validate(stamp)){
System.out.println("读取完成");
return data;
}
// 锁升级 --》读锁
try{
stamp = lock.readLock();
// 读
return data;
}finally {
lock.unlockRead(stamp);
}
}
public void write(int newData){
long stamp = lock.writeLock();
try{
this.data = newData;
}finally {
lock.unlock(stamp);
}
}
}
缺点:
- StampedLock 不支持条件变量
- StampedLock 不支持可重入
二、Semaphore
信号量,用来限制能同时访问共享资源的线程上限。
例:
public static void main(String[] args) {
// 1. 创建semaphore对象
Semaphore semaphore = new Semaphore(3);
// 2. 10个线程同时运行
for(int i = 0; i < 10; i++){
new Thread(() -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("running");
Thread.sleep(1000);
System.out.println("end");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}).start();
}
}
Semaphore应用
- 使用Semaphore限流(单机版),在访问高峰期,让请求线程阻塞,高峰期过去在释放许可,它只适合限制单机线程数量,并且仅是限制线程数,而不是限制资源数(例如连接数,对比Tomcat LimitLatch实现)
- 用Semaphore实现简单连接池,替代wait notify,性能和可读性更好(线程数和数据库连接数是相等的)
Semaphore原理
1、加解锁流程
Semaphore 有点像一个停车场,permits 就好像停车位数量,当线程获得了permits就像是获得了停车位,然后停车场显示空余车位减一。
刚开始,permits(state) 为 3, 这时 5个线程来获取资源
假设其中 Thread-1,Thread-2,Thread-4 竞争成功,而Thread-0 和 Thread-3 竞争失败,进入 AQS 队列park阻塞
这时 Thread-4 释放了 permits,状态如下
接下来,Thread-0 竞争成功,permits 再次设置为0,设置自己为head节点,断开原来的head节点,unpark 接下来的 Thread-3节点,但由于 permits 是0,因此 Thread-3 在尝试不成功后再次进入 park状态。
获取许可源码如下:
// 构造方法
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
NonfairSync(int permits) {
super(permits);
}
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
}
// 最终将state设为传进入的数字
Sync(int permits) {
setState(permits);
}
// 获取许可过程
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
// > 0 表示获取到了许可
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
释放许可源码如下:
public void release() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
// 释放成功返回true
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
// 唤醒后继节点
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
三、CountdownLatch
用来进行线程同步协作,等待所有线程完成倒计时。
其中构造参数用来初始化等待计数值,await() 用来等待计数归零,countDown() 用来让计数减一。
// 构造方法(把state设为传进来的数值)
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
Sync(int count) {
setState(count);
}
// await()
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
// state == 0 时,直接运行,不阻塞
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
// countDown
public void countDown() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// 将state - 1
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
四、CyclicBarrier
循环栅栏,用来进行线程协作,等待线程满足某个计数。构造时设置【计数个数】,每个线程执行到某个需要“同步”的时刻调用 await()方法进行等待,当等待的线程数满足【计数个数】时,继续执行。
使用举例:
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(2);
// 第二个参数用于cycleBarrier减为0时统一做一些事,CyclicBarrier可循环使用,于countDownLatch不同
CyclicBarrier barrier = new CyclicBarrier(2, () -> {
System.out.println("task1, task2 finish");
});
for(int i = 0; i <= 3; i++){
service.submit(() -> {
System.out.println("task1 begin...");
try {
Thread.sleep(1000);
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
});
service.submit(() -> {
System.out.println("task2 begin...");
try {
Thread.sleep(1000);
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
}
service.shutdown();
}
五、线程安全集合类概述
线程安全集合类可以分为三大类:
-
遗留的线程安全集合如 Hashtable,Vector
-
使用 Collections 装饰的线程安全集合,如:
- Collections.synchronizedCollection - Collections.synchronizedList - Collections.synchronizedMap - Collections.synchronizedSet - Collections.synchronizedSortedMap - Collections.synchronizedSortedSet
-
java.util.concurrent.*
可以发现juc下的线程安全集合类包含三类关键词:
Blocking、CopyOnWrite、Concurrent -
Bolcking 大部分基于锁,并提供用来阻塞的方法
-
CopyOnWrite 之类容器修改开销相对较重
-
Concurrent类型容器
- 内部很多操作使用cas优化,一般可以提供较高吞吐量 - 弱一致性。遍历时弱一致性,例如,当利用迭代器遍历时,如果容器发生修改,迭代器仍然可以继续遍历,这时内容是旧的;求大小弱一致性,size操作未必是100%准确;读取弱一致性;遍历时如果发生了修改,对于非安全容器来讲,使用 fail-fast 机制也就是让遍历立即失败,抛出 ConcurrentModificationException,不再继续遍历。