gpt4 book ai didi

java - 如果可以使用synchronized(this),为什么还要使用ReentrantLock?

转载 作者:行者123 更新时间:2023-12-02 04:17:02 25 4
gpt4 key购买 nike

我试图理解如果可以使用synchronized (this),那么并发锁为何如此重要。在下面的虚拟代码中,我可以执行以下任一操作:

  1. 同步整个方法或同步易受攻击的区域 (synchronized(this){...})
  2. 或者使用 ReentrantLock 锁定易受攻击的代码区域。

代码:

    private final ReentrantLock lock = new ReentrantLock(); 
private static List<Integer> ints;

public Integer getResult(String name) {
.
.
.
lock.lock();
try {
if (ints.size()==3) {
ints=null;
return -9;
}

for (int x=0; x<ints.size(); x++) {
System.out.println("["+name+"] "+x+"/"+ints.size()+". values >>>>"+ints.get(x));
}

} finally {
lock.unlock();
}
return random;
}

最佳答案

一个ReentrantLock非结构化,与同步构造不同——即您不需要使用 block 结构来锁定,甚至可以跨方法持有锁。一个例子:

private ReentrantLock lock;

public void foo() {
...
lock.lock();
...
}

public void bar() {
...
lock.unlock();
...
}

这样的流程不可能通过同步构造中的单个监视器来表示。

<小时/>

除此之外,ReentrantLock 支持 lock pollinginterruptible lock waits that support time-outReentrantLock 还支持configurable fairness policy ,允许更灵活的线程调度。

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 可能也可以是 more scalable ,在更高的竞争下表现得更好。您可以阅读更多相关信息here .

然而,这一说法受到了质疑;请参阅以下评论:

In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.

<小时/>

什么时候应该使用ReentrantLock?根据该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 and Project Loom有关。 。在虚拟线程的(新)世界中,底层调度程序使用 ReentrantLock 比使用 synchronized 能够更好地工作,至少在最初的 Java 15 版本,但稍后可能会进行优化。

In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a synchronized block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (the synchronized block/method is exited) the thread is unpinned.

If you have a common I/O operation guarded by a synchronized, replace the monitor with a ReentrantLock to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performance StampedLock if you can).

关于java - 如果可以使用synchronized(this),为什么还要使用ReentrantLock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56655660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com