我需要同步对Java中不可变类型的访问吗? [英] Do I need to synchronize access to immutable types in Java?

查看:65
本文介绍了我需要同步对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.

推荐答案

从技术上讲,您需要将其设置为finalvolatile或阅读,并使用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并发实践.

A great book on this is Java Concurrency in Practice.

这篇关于我需要同步对Java中不可变类型的访问吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆