ReentrantLock是非结构化的,不像同步结构——也就是说,你不需要使用块结构来锁,甚至可以跨方法持有锁。一个例子:
private ReentrantLock lock;
public void foo() {
...
lock.lock();
...
}
public void bar() {
...
lock.unlock();
...
}
这种流不可能通过同步构造中的单个监视器来表示。
除此之外,ReentrantLock还支持锁轮询和支持超时的可中断锁等待。ReentrantLock还支持可配置的公平策略,允许更灵活的线程调度。
The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.
ReentrantLock也可能更具可伸缩性,在更高的争用下性能会更好。你可以在这里阅读更多相关内容。
然而,这一说法遭到了质疑;请看下面的评论:
在重入锁测试中,每次都会创建一个新锁,因此不存在排他锁,结果数据无效。此外,IBM链接没有提供底层基准测试的源代码,因此无法确定测试是否正确执行。
什么时候应该使用ReentrantLocks?根据developerWorks的文章…
The answer is pretty simple -- use it when you actually need something it provides that synchronized doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use ReentrantLock. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.
在不久的将来,与Java 15和Project Loom相关的最后一个方面将变得更加重要。在虚拟线程的(新)世界中,底层调度器使用ReentrantLock比使用synchronized工作得更好,至少在最初的Java 15版本中是这样,但以后可能会进行优化。
在当前的Loom实现中,虚拟线程可以在两种情况下固定:当堆栈上有本机帧时——当Java代码调用本机代码(JNI),然后JNI再调用Java时——以及在同步块或方法中时。在这些情况下,阻塞虚拟线程将阻塞承载它的物理线程。一旦本机调用完成或监视器被释放(同步块/方法被退出),线程就被解除固定。
如果你有一个常用的I/O操作由synchronized保护,用ReentrantLock替换监视器,让你的应用程序在我们修复监视器固定之前充分受益于Loom的可伸缩性提升(或者,如果可以的话,更好的是使用性能更高的StampedLock)。