【1】-3 Reentrance Lockout (重入锁死)
来源:互联网 发布:c语言中char是几位 编辑:程序博客网 时间:2024/06/16 09:03
Reentrance lockout 【重入锁死】 is a situation similar to deadlock and nested monitor lockout. Reentrance lockout is also covered in part in the texts on Locks and Read / Write Locks.
Reentrance lockout may occur if a thread reenters a Lock, ReadWriteLock or some other synchronizer that is not reentrant. Reentrant means that a thread that already holds a lock can retake it. Java's synchronized blocks are reentrant. Therefore the following code will work without problems:
public class Reentrant{ public synchronized outer(){ inner(); } public synchronized inner(){ //do something }}
Notice how both outer()
and inner()
are declared synchronized, which in Java is equivalent to asynchronized(this)
block. If a thread calls outer()
there is no problem calling inner() from inside outer()
, since both methods (or blocks) are synchronized on the same monitor object ("this").
If a thread already holds the lock on a monitor object, it has access to all blocks synchronized on the same monitor object. This is called reentrance. The thread can reenter any block of code for which it already holds the lock.
The following Lock
implementation is not reentrant:
inner()
都定义了synchronized ,在java中 这等价于 synchronized(this)
。inner()
时没问题的,尽管两个方法(或块)在同一个监控对象object ("this") 上加了synchronized 。public class Lock{ private boolean isLocked = false; public synchronized void lock() throws InterruptedException{ while(isLocked){ wait(); } isLocked = true; } public synchronized void unlock(){ isLocked = false; notify(); }}
If a thread calls lock()
twice without calling unlock()
in between, the second call to lock()
will block. A reentrance lockout has occurred.
To avoid reentrance lockouts you have two options:
- Avoid writing code that reenters locks
- Use reentrant locks
Which of these options suit your project best depends on your concrete situation. Reentrant locks often don't perform as well as non-reentrant locks, and they are harder to implement, but this may not necessary be a problem in your case. Whether or not your code is easier to implement with or without lock reentrance must be determined case by case.
lock()
两次而没有调用 unlock()两次,第二次调用 lock()时将会阻塞。
一个
重入锁死 问题
就出现了:
为了解决这个问题你有2中方案:
1、编写代码时避免再次获取已经持有的锁。
2、使用可重入锁。
至于选择哪个最适合你的项目,的视情况具体而定。
- 【1】-3 Reentrance Lockout (重入锁死)
- 函数可重入(reentrance)
- How to fix a Lockout && cphulkdwhitelist
- 重入锁死
- 重入锁死
- java 重入锁死
- Java并发系列-21、重入锁死
- 3/1
- 3-1
- 3-1
- 1-3
- -3+1
- -3+1
- -3+1
- -3+1
- 1-3
- 3-1
- 1-3
- H264中的CABAC及FFMPEG中的实现
- linux进程间通讯-命名管道
- 强大的图片加载框架Fresco的使用
- 使用RecyclerView 简单实现QQ好友列表展开效果
- Android OrmLite与SQLite数据库操作
- 【1】-3 Reentrance Lockout (重入锁死)
- Android研发安全3-Service安全
- ConvenientBanner
- 现有‘abcdefghijkl’12个字符,将其所有的排列按字典序进行排序,给出任意一组排列,说出这租排列在所有排列中是第几小的
- 洛谷 P1372 又是毕业季I 数论
- Python科学计算环境推荐——Anaconda
- static和final修饰的变量之间的区别
- COLLECTING DATA FROM A PRIVATE LORAWAN SENSOR NETWORK INTO ELASTIC
- 【1】-4 Semaphores