gpt4 book ai didi

java - 为什么要将虚拟对象作为 block 级同步的参数传递?

转载 作者:行者123 更新时间:2023-12-05 00:57:53 25 4
gpt4 key购买 nike

在 Spring 源代码中找到这段代码。这是将 XML 文件转换为 Bean Tree 的第一步。

/** Synchronization monitor for the "refresh" and "destroy" */
private final Object startupShutdownMonitor = new Object();

public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
}

最佳答案

这个习语用于更精细的级别同步。这是 Java tutorial 的摘录.您本可以使用synchronized(this),但这会锁定整个对象

Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();

public void inc1() {
synchronized(lock1) {
c1++;
}
}

public void inc2() {
synchronized(lock2) {
c2++;
}
}
}

从 Java 5 开始,java 引入了 Lock提供更多功能的抽象。因此,您可以执行以下操作而不是 synchronized(obj)。阅读更多 details here

Lock lock = new ReentrantLock();

lock.lock();

c1++;

lock.unlock();

关于java - 为什么要将虚拟对象作为 block 级同步的参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9095993/

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