Do I need to synchronize access to immutable types in Java?(我是否需要同步对 Java 中不可变类型的访问?)
问题描述
假设我有这个课程:
class Zoo
{
    protected String bearName;
    protected Double trainerSalary;
    protected Integer monkeyCount;
}
可以一个线程写入这些字段,另一个线程读取它们,而不需要 synchronized 访问 Zoo 对象吗?
Can one thread write to these fields, and another one read them, without requiring synchronized access to the Zoo object? 
注意:这些值可以彼此分开处理,因此在读取 monkeyCount 时更改 trainerSalary 并不重要.
Note: these values can be treated separate from one another, so it doesn't matter that the trainerSalary is changed while the monkeyCount is read.
编辑:
澄清一下,这些字段是可变的;只有它们引用的对象是不可变的.
Just to clarify, the fields are mutable; only their referenced objects are immutable.
推荐答案
从技术上讲,您需要使它们 final、volatile 或读取 and使用 synchronzied 编写它们以保证阅读器将读取最新的值.正如您现在所拥有的,如果一个线程写入一个值,则不能保证另一个线程将读取相同的值.这是因为读取线程可能会看到缓存的值.多核 CPU 和不同级别的缓存更有可能出现这种情况.
Technically you need to make them final, volatile or read and write them using synchronzied to guarantee that the reader will read the most up-to-date value. As you have it right now, if one thread writes in a value, there's no guarantee that another thread will read the same value. This is because the the reading thread may see a cached valued. This is more likely with multi-core CPUs and various levels of cache.
Java 并发实践是一本很好的书.
这篇关于我是否需要同步对 Java 中不可变类型的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我是否需要同步对 Java 中不可变类型的访问?
				
        
 
            
        - GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
 - 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
 - Eclipse 的最佳 XML 编辑器 2022-01-01
 - 未找到/usr/local/lib 中的库 2022-01-01
 - 如何指定 CORS 的响应标头? 2022-01-01
 - 获取数字的最后一位 2022-01-01
 - 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
 - 转换 ldap 日期 2022-01-01
 - 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
 - java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
 
						
						
						
						
						
				
				
				
				