gpt4 book ai didi

java - 只读同步

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

Effective Java - 第 66 条(第 2 版)规定

In fact, synchronization has no effect unless both read and write operations are synchronized.

假设我有一个对象正在由一个线程更新并由另一个线程读取。出于通信目的,需要在读取线程上进行同步,因为如上所述

In other words, the synchronization on these methods is used solely for its communication effects, not for mutual exclusion.

但是如果写入是由单个线程执行的,为什么我们不能在写入期间不使用同步来摆脱困境?

最佳答案

因为 happens-before 在 Java 内存模型中的工作原理。要允许线程 2 看到线程 1 写入的变量的新值,您需要在此写入和读取之间建立 发生之前 关系 ( https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/happens-before.html )。实现此目的的方法之一是使用同步(synchronized block /方法、 volatile AtomicXXX),因为释放锁总是在获取锁之前发生对于同一锁,写入 volatile 变量发生在后续读取相同 volatile 变量之前。对于同一变量,AtomicXXX.set() 发生在 AtomicXXX.get() 之前。

关于java - 只读同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49264632/

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