在不久的将来会变得更加相关的最后一个方面与 Java 15 和 Project Loom.在虚拟线程的(新)世界中,与 synchronized 相比,底层调度程序使用 ReentrantLock 能够更好地工作,至少在最初的 Java 15 版本,但可能会在以后进行优化.在当前的 Loom 实现中,可以在两种情况下固定虚拟线程:当堆栈上有本机框架时——当 Java 代码调用本机代码(JNI)然后回调到 Java 时——以及当在一个synchronized 块或方法.在这些情况下,阻塞虚拟线程将阻塞承载它的物理线程.一旦本机调用完成或监视器释放(synchronized 块/方法退出),线程就会被取消固定.如果您有一个由 synchronized 保护的常见 I/O 操作,请用 ReentrantLock 替换监视器,让您的应用程序甚至在我们之前从 Loom 的可扩展性提升中充分受益修复监视器固定(或者,如果可以的话,最好使用性能更高的 StampedLock).I'm trying to understand what makes the lock in concurrency so important if one can use synchronized (this). In the dummy code below, I can do either:synchronized the entire method or synchronize the vulnerable area (synchronized(this){...})OR lock the vulnerable code area with a ReentrantLock.Code: 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;} 解决方案 A ReentrantLock is unstructured, unlike synchronized constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:private ReentrantLock lock;public void foo() { ... lock.lock(); ...}public void bar() { ... lock.unlock(); ...}Such flow is impossible to represent via a single monitor in a synchronized construct.Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.This claim has been contested, however; see the following comment:When should you use ReentrantLocks? According to that developerWorks article...One final aspect that's gonna become more relevant in the near future has to do with Java 15 and Project Loom. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with ReentrantLock than it's able to do with synchronized, that's true at least in the initial Java 15 release but may be optimized later. 这篇关于如果可以使用 synchronized(this),为什么要使用 ReentrantLock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
06-16 08:34