Lock入门
跟同步关键字有同样的内存语义。
与Synchronized的比较
对比
与 synchronized 相比,ReentrantLock 更灵活。
- 他支持阻塞等待/可中断的等待/非阻塞的获取/超时等待 等
- 阻塞期间不会响应中断
- 支持更细粒度的可重入锁
代码示例
// ************************** Synchronized **************************
// 1.用于代码块
synchronized (this) {}
// 2.用于对象
synchronized (object) {}
// 3.用于方法
public synchronized void test () {}
// 4.可重入
for (int i = 0; i < 100; i++) {
synchronized (this) {}
}
// ************************** ReentrantLock **************************
public void testLock() throw Exception {
// 1.初始化选择公平锁、非公平锁
ReentrantLock lock = new ReentrantLock(true);
// 2.可用于代码块
lock.lock();
try {
try {
// 3.支持多种加锁方式,比较灵活; 具有可重入特性
if(lock.tryLock(100, TimeUnit.MILLISECONDS)){ }
} finally {
// 4.手动释放锁
lock.unlock()
}
} finally {
lock.unlock();
}
}
ReentrantLock
API
方法 | 描述 |
lock | 获取锁的方法,若锁被其他线程获取,则等待(阻塞) |
lockinterruptibly | 在锁的获取过程中可以中断当前线程 |
tryLock | 尝试非阻塞地获取锁,立即返回 |
unlock | 释放锁 |
Tips:
根据Lock接口的源码注释,Lock接口的实现, 具备和同步关键字同样的内存语义。
实例
可重入
- 可重入的定义:一个 Lock 对象可以被同一线程加锁多次
- 注意一点:一定要在 finally 中进行解锁,避免死锁
public class ReentrantDemo1 {
private static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
lock.lock(); // block until condition holds
try {
System.out.println("第一次获取锁");
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
lock.lock();
System.out.println("第二次获取锁了");
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
} finally {
lock.unlock();
lock.unlock();
}
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
// 如果不释放,此时其他线程是拿不到锁的
new Thread(() -> {
System.out.println(Thread.currentThread() + " 期望抢到锁");
lock.lock();
System.out.println(Thread.currentThread() + " 线程拿到了锁");
}).start();
}
}
可响应中断
中断只是标记线程应该被中断,但不是马上停止
- lockInterruptibly 可在等待的过程响应中断
// 可响应中断
public class LockInterruptiblyDemo1 {
private Lock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
LockInterruptiblyDemo1 demo1 = new LockInterruptiblyDemo1();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
demo1.test(Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
Thread.sleep(500); // 等待0.5秒,让thread1先执行
thread2.start();
Thread.sleep(2000); // 两秒后,中断thread2
thread2.interrupt();
}
public void test(Thread thread) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + ", 想获取锁");
lock.lockInterruptibly(); //注意,如果需要正确中断等待锁的线程,必须将获取锁放在外面,然后将InterruptedException抛出
try {
System.out.println(thread.getName() + "得到了锁");
Thread.sleep(10000); // 抢到锁,10秒不释放
} finally {
System.out.println(Thread.currentThread().getName() + "执行finally");
lock.unlock();
System.out.println(thread.getName() + "释放了锁");
}
}
}
lockInterruptibly()/lock() 区别
- lockInterruptibly 可以响应中断
- 即,阻塞时被中断,可以 throw exception
- lock() 不响应中断
- 被 interrupt 后不会立即中断,而是继续等待
ReentrantReadWriteLock 读写锁
读写锁定义
- 维护一对关联锁,一个用于只读操作,一个用于写入。
- 读锁可以由多个读线程同时持有,写锁是排他的。
- 写锁的时候可以读。
- 读锁的时候不可写。
- 适合读取线程比写入线程多的场景,改进互斥锁的性能。
- 示例场景:缓存组件、集合的并发线程安全性改造。
锁降级定义
- 锁降级指的是写锁降级成为读锁。
- 当前线程拥有的写锁的同时,再获取到读锁,随后释放写锁的过程。
- 写锁是线程独占,读锁是共享,所以写->读是升级。(读->写, 是不能实现的)
使用读写锁防止缓存雪崩(锁降级实例)
- 问题:
- 当没有读写锁时,大量请求在没有命中缓存的情况下,全部打到 db 上。
- 有可能出现数据不一致的情况。
- 锁降级:写锁 -> 读锁
- 释放了读锁,才可以加写锁
- 不会造成死锁!!
- 缓存雪崩
- 在没有命中缓存的情况下,释放读锁,加写锁。防止多个线程同时读 db,导致雪崩
- Park/Unpark底层实现是用的 Unsafe 机制
// 缓存示例
public class CacheDataDemo {
// 创建一个map用于缓存
private Map<String, Object> map = new HashMap<>();
private static ReadWriteLock rwl = new ReentrantReadWriteLock();
public static void main(String[] args) {
// 1 读取缓存里面的数据
// cache.query()
// 2 如果换成没数据,则取数据库里面查询 database.query()
// 3 查询完成之后,数据塞到塞到缓存里面 cache.put(data)
}
public Object get(String id) {
Object value = null;
// 首先开启读锁,从缓存中去取(防止数据不一致,要释放了读锁才会加写锁)
rwl.readLock().lock();
try {
value = map.get(id);
if (value == null) {
// TODO database.query(); 全部查询数据库 ,缓存雪崩
// 必须释放读锁,否则无法加写锁
rwl.readLock().unlock();
// 如果缓存中没有释放读锁,上写锁。防止多个相同的查询请求同时查询数据库
rwl.writeLock().lock(); // 所有线程在此处等待 1000 1 999 (在同步代码里面再次检查是否缓存)
try {
value = map.get(id);
// 双重检查。如果已经写了缓存,则其他线程直接获取
if (mvalue == null) {
// TODO value = ...如果缓存没有,就去数据库里面读取
}
// 写锁降级读锁,保证了之前读取操作的数据一致性。(在释放读锁前,其他线程无法修改缓存的值)
rwl.readLock().lock();
} finally {
rwl.writeLock().unlock(); // 释放写锁@
}
}
/* 在这里又进行了一系列操作,在操作过程中,有可能数据改变导致缓存内容改变
此时,要在写锁中加入读锁,防止类似于 幻读,脏读 等的产生
*/
} finally {
rwl.readLock().unlock();
}
return value;
}
}
Condition
概念
可以更细粒度的的控制等待,与 ReentrantLock 配合使用
- 与 synchronized 中 wait()/notify()/notifyAll()对比
- 用于替代 wait()/notify()
- 粒度更细
- Condition 则提供了多个等待集合,可以指定具体操作的集合,粒度更细。
- wait()/notify() 只有一个等待集合,notify 只能唤醒 waiters 中的一个或多个,没办法指定具体唤醒线程
- 是否释放锁:都会释放已持有的锁(不释放会死锁)
- 底层:park/unpark
使用场景
JDK 中队列的实现
- 多线程读写队列,写入数据后,唤醒读取线程继续执行;读取数据后,通知写入队列继续执行
// condition 实现队列线程安全。
public class QueueDemo {
final Lock lock = new ReentrantLock();
// 指定条件的等待 - 等待有空位
final Condition notFull = lock.newCondition();
// 指定条件的等待 - 等待不为空
final Condition notEmpty = lock.newCondition();
// 定义数组存储数据
final Object[] items = new Object[100];
int putptr, takeptr, count;
// 写入数据的线程,写入进来
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) // 数据写满了
notFull.await(); // 写入数据的线程,进入阻塞
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal(); // 唤醒指定的读取线程
} finally {
lock.unlock();
}
}
// 读取数据的线程,调用take
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await(); // 线程阻塞在这里,等待被唤醒
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal(); // 通知写入数据的线程,告诉他们取走了数据,继续写入
return x;
} finally {
lock.unlock();
}
}
}
实例
HashMap 的线程安全改造
HashTable 是如何实现线程安全的
- get/put 操作都是通过 synchronized 关键字保证线程安全,导致每次只能有一个线程 get/put
- synchronized 修饰方法时锁定的是调用该方法的对象
使用读写锁改造HashMap
- 将 HashMap 改造为线程安全的类(这里只是简单的改造 get/put 方法)
- 使用场景:读多写少,可以多个线程同时读;但只有一个线程可写(全部读完后才开始写操作)。
public class ThreadSafeMap<K, V> extends HashMap<K, V> {
//使用读写锁保证线程安全
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
@Override
public V get(Object key) {
V value;
try {
readLock.lock();
return super.get(key);
} finally {
readLock.unlock();
}
}
@Override
public V put(K key, V value) {
V ret;
try {
writeLock.lock();
return super.put(key, value);
} finally {
writeLock.unlock();
}
}
}
自实现 ReentrantLock
- 提示:
- 要使用 pack/unpack 实现同步
- wait()/notify() 必须要在同步代码块(monitor object)
- 注意:
- 一定要在 unlock() 成功以后在进行 uppark
- 非公平的,有可能在 unlock 的 CAS 执行成功后,unpark waiter 之前,有新的线程进行了 lock
/**
* 自己手动实现的一个 reentrantLock
*
*/
public class GzyLock implements Lock {
//需要 CAS 自旋的方式去实现
//模仿 monitor obj 的重量级锁 有一个 owner
private static AtomicReference<Thread> owner = new AtomicReference<>();
private static LinkedBlockingDeque<Thread> waiters = new LinkedBlockingDeque<>();
@Override
public void lock() {
boolean addQueue = true;
while (!tryLock()){
//第一次进来会放到queue
if(addQueue) {
//如果没有获取到锁,就先存到 queue
waiters.offer(Thread.currentThread());
addQueue = false;
}else {
//park 等待被唤醒。这里不能用 wait/notify 因为需要在同步代码块用
LockSupport.park();
}
//唤醒后尝试争抢,没抢到继续等
}
//抢到锁,移除掉
waiters.remove(Thread.currentThread());
}
@Override
public boolean tryLock() {
//适用当前线程尝试加锁
return owner.compareAndSet(null, Thread.currentThread());
}
@Override
public void unlock() {
//unlock 的时候,要唤醒等待线程
//如果释放锁成功了,才会唤起
//这里用 if 是因为,一定不会出现 循环
if (owner.compareAndSet(Thread.currentThread(), null)) {
//一次唤醒所有在等待队列的
for (Thread waiter : waiters) {
//唤起等待队列的线程
LockSupport.unpark(waiter);
}
}
}
public static void main(String[] args) throws InterruptedException {
Adder adder = new Adder();
for (int j = 0; j < 10; j++) {
Thread addThread = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
adder.add();
}
});
addThread.start();;
}
Thread.sleep(1000L);
System.out.println(adder.i);
}
static class Adder{
Lock lock = new GzyLock();
int i = 0;
public void add(){
lock.lock();
try {
i++;
}finally {
lock.unlock();
}
}
}
}