…
好记性不如烂笔头,今天讨论讨论读写锁。
阅读须知:本文使用Quarkus框架Java语言编写。
介绍
什么是读写锁?
- 读写锁(Readers-Writer Lock)顾名思义就是读锁写锁,读锁允许多个线程同时获得,因为读操作本身是线程安全的,多个线程的读取操作不存在破坏数据的情况。而写锁则是互斥锁(不然就会发生本文说到的情况),不允许多个线程同时获得写锁。
- 写操作和读操作也是互斥的。
- Java的并发就含有读写锁ReadWriteLock。在多线程场景中,如果某个对象处于改变状态,可以用写锁加锁,这样所有做读操作对象的线程,在获取读锁时就会block住,直到写锁释放。
经典案例
小明小红小刚使用同一张银行卡卡号,在同一时间内进行频繁操作,一个频繁查看余额 ¥–>100 ¥–>99 ¥–>101 … ,有人一直存款2块 +2 +2 +2…,有人取钱取出1块 -1 -1 -1…,若是三个人都循环十次自己的操作,正常情况下最终余额应该是110,但如果充值和扣费是在两个线程同时进行,而且各算各的,再分别用自己的计算结果去覆盖余额,最终会导致计算不准确,结果余额不等110。
提问!
为什么会出现不等于的情况?
提示:三个线程拼命抢夺资源,当A线程修改值之前B刚好拿到余额count 那么会发生什么有趣的事情呢?
不妨大胆思考一下此时的余额或者之后的余额会如何?
3
…
…
…
…
.
2
…
…
…
…
.
1
…
…
…
…
.
没错!!!
当A线程修改值之前B刚好拿到余额,
A不知道B拿到了count,
若A读取count=100,之后存入2块,余额102
B在取出1块之前读取到count=100,取出1块,余额99
如此就很明显看到问题所在
此处附上实验代码
package org.acme.LockDemo;
import io.quarkus.logging.Log;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class AccountBalanceService {
// 账户余额,假设初始值为100
int accountBalance = 100;
/**
* 查询余额
* @return
*/
public int get() {
// 模拟耗时的操作
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
return accountBalance;
}
/**
* 模拟充值操作
* @param value
* @throws InterruptedException
*/
public void deposit(int value) {
// 先将accountBalance的值存入tempValue变量
int tempValue = accountBalance;
Log.infov("start deposit, balance [{0}], deposit value [{1}]", tempValue, value);
// 模拟耗时的操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tempValue += value;
// 用tempValue的值覆盖accountBalance,
accountBalance = tempValue;
Log.infov("end deposit, balance [{0}]", tempValue);
}
/**
* 模拟扣费操作
* @param value
* @throws InterruptedException
*/
public void deduct(int value) {
// 先将accountBalance的值存入tempValue变量
int tempValue = accountBalance;
Log.infov("start deduct, balance [{0}], deposit value [{1}]", tempValue, value);
// 模拟耗时的操作
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tempValue -= value;
// 用tempValue的值覆盖accountBalance
accountBalance = tempValue;
Log.infov("end deduct, balance [{0}]", tempValue);
}
}
package org.acme.LockDemoTest;
import io.quarkus.logging.Log;
import io.quarkus.test.ju
nit.QuarkusTest;
import org.acme.LockDemo.AccountBalanceService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.inject.Inject;
import java.util.concurrent.CountDownLatch;
@QuarkusTest
public class LockTest {
@Inject
AccountBalanceService account;
@Test
public void test() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
int initValue = account.get();
final int COUNT = 10;
// 这是个只负责读取的线程,循环读10次,每读一次就等待50毫秒
new Thread(() -> {
for (int i=0;i<COUNT;i++) {
// 读取账号余额
Log.infov("current balance {0}", account.get());
}
latch.countDown();
}).start();
// 这是个充值的线程,循环充10次,每次存2元
new Thread(() -> {
for (int i=0;i<COUNT;i++) {
account.deposit(2);
}
latch.countDown();
}).start();
// 这是个扣费的线程,循环扣10次,每取1元
new Thread(() -> {
for (int i=0;i<COUNT;i++) {
account.deduct(1);
}
latch.countDown();
}).start();
latch.await();
int finalValue = account.get();
Log.infov("finally, current balance {0}", finalValue);
Assertions.assertEquals(initValue + COUNT, finalValue);
}
}
- 上述代码中,有以下几点需要注意
- 在主线程中新增了三个子线程,分别执行查询、充值、扣费的操作,可见deposit和deduct方法是并行执行的
- 初始余额100,充值一共20元,扣费一共10元,因此最终正确结果应该是110元
- 为了确保三个子线程全部执行完毕后主线程才退出,这里用了CountDownLatch,在执行latch.await()的时候主线程就开始等待了,等到三个子线程把各自的**latch.await()**都执行后,主线程才会继续执行
- 最终会检查余额是否等于110
- 最终结论,测试失败,不等于110
解决办法可以有:
- 用传统的synchronized关键字修饰三个方法
- java包的读写锁
这里使用Quarkus的@Lock解决
@Lock
只需要将@Lock注解注解到类、方法上即可,该注解类型有三种选择:读锁,写锁,无锁。
以下是Quarkus的@Lock注解源码
@InterceptorBinding
@Inherited
@Target(value = { TYPE, METHOD })
@Retention(value = RUNTIME)
public @interface Lock {
/**
*
* @return the type of the lock
*/
@Nonbinding
Type value() default Type.WRITE;
/**
* If it's not possible to acquire the lock in the given time a {@link LockException} is thrown.
*
* @see java.util.concurrent.locks.Lock#tryLock(long, TimeUnit)
* @return the wait time
*/
@Nonbinding
long time() default -1l;
/**
*
* @return the wait time unit
*/
@Nonbinding
TimeUnit unit() default TimeUnit.MILLISECONDS;
public enum Type {
/**
* Acquires the read lock before the business method is invoked.
*/
READ,
/**
* Acquires the write (exclusive) lock before the business method is invoked.
*/
WRITE,
/**
* Acquires no lock.
* <p>
* This could be useful if you need to override the behavior defined by a class-level interceptor binding.
*/
NONE
}
}
那么如何使用呢?
- 使用之前我们需要了解到,@Lock默认会为类的每一个方法添加写锁
- Lock.Type.READ表示将get方法改为读锁,Lock.Type.NONE表示该方法方法没有锁
被修改的代码如下:
package org.acme.LockDemo;
import io.quarkus.logging.Log;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
@Lock
public class AccountBalanceService {
/**
* 查询余额
* @return
*/
@Lock(value=Lock.Type.READ)
public int get() {
// 模拟耗时的操作
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
return accountBalance;
};
// 。。。。。。。。
}
研究结论
- 当deposit方法或者deduct方法被调用时,其他线程在调用deposit、deduct、get方法时都被阻塞了,必须等deposit执行完毕,它们才重新去抢锁
- 当deposit方法或者deduct方法没有被调用时,get方法可以被调用,并且可以在多个线程同时调用
讨论
这个案例看起来很好玩,读写锁也很好用,那么性能上,读写锁可以在哪些场景上不能使用呢?
3
…
…
…
…
.
2
…
…
…
…
.
1
…
…
…
…
.
- 从以上例子可以看出,读写锁看似十分安全,但是代价不小(当一个线程运行标注着写锁的方法时,其他线程都需处于等待状态,若是还有网络等延迟问题,该程序简直处于噩梦级别)
- 在并发性能要求较高的场景下要慎用,可以考虑乐观锁等方式来降低等待代价**