When to select ReentrantLock over synchronized
什么时候选择用ReentrantLock 代替synchronized
Listing 1. Protecting a block of code with ReentrantLock.
清单1.用ReentrantLock保护代码块。
Or even rewrite our existing synchronized code in terms of ReentrantLock?
或者甚至用ReentrantLock重写我们现有的synchronized代码?
Instead, make the decision on the basis of whether you need the power of ReentrantLock.
相反,应当根据您是否需要ReentrantLock的能力来作出选择。
The stated goal was to answer the question, "Which is faster, synchronization or ReentrantLock?"
此举的目的是回答以下问题:“哪一个更快,同步还是 ReentrantLock?”
Before entering the critical section, the lock method of the ReentrantLock object is invoked to try and obtain the lock.
在进入关键部分之前,调用ReentrantLock对象的lock方法,尝试并获得锁。
However, the existence of these obvious benefits are not a good enough reason to always prefer ReentrantLock to synchronized.
但是,这些明显存在的好处,还不足以成为用ReentrantLock代替synchronized的理由。
It purports to measure the performance costs of synchronization and ReentrantLock, techniques used to coordinate the action of multiple threads.
这个基准的目的是要度量同步和ReentrantLock的性能代价,它们是用于协调多个线程的行为的不同技术。
You'll see that atomic variables offer an additional improvement over ReentrantLock, which already had a big advantage over synchronization.
您将看到,虽然ReentrantLock 拥有比同步更多的优点,但相对于 ReentrantLock,原子变量提供了其他改进。
While that column showed how the new ReentrantLock class is a more scalable replacement for synchronization, for some problems there is an even better approach.
虽然该专栏说明了新的ReentrantLock类如何可以更可伸缩地替代同步,但是对于一些问题,还有更好的解决方法。
Because so little work is done in each unit of work, the graphs below probably understate the scalability benefits of atomic variables compared to ReentrantLock.
因为在每个工作单元中完成的工作很少,所以下图可能无法完全地说明与ReentrantLock相比,原子变量具有哪些可伸缩性优点。
Similarly, attempting to acquire an intrinsic lock (enter a synchronized block) cannot be interrupted, but ReentrantLock supports an interruptible acquisition mode.
类似地,尝试获取一个内部锁的操作(进入一个synchronized块)是不能被中断的,但是ReentrantLock支持可中断的获取模式。
This means that when many threads are all contending for the same lock, the total throughput is generally going to be better with ReentrantLock than with synchronized.
这意味着当许多线程都在争用同一个锁时,使用ReentrantLock的总体开支通常要比synchronized少得多。
The ReentrantLock class, which implements Lock, has the same concurrency and memory semantics as synchronized, but also adds features like lock polling, timed lock waits, and interruptible lock waits.
ReentrantLock类实现了Lock ,它拥有与 synchronized相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性。
The ReentrantLock class, which implements Lock, has the same concurrency and memory semantics as synchronized, but also adds features like lock polling, timed lock waits, and interruptible lock waits.
ReentrantLock类实现了Lock ,它拥有与 synchronized相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性。
应用推荐