简体   繁体   English

Java并发-创建后更改可变对象

[英]Java concurrency - change mutable object after creation

I've created an Employee Object in Thread A. An Employee class is mutable . 我在线程A中创建了一个Employee对象。一个Employee类是可变的。 In the same thread A, I've updated employee salary and change other fields. 在同一线程A中,我更新了员工薪水并更改了其他字段。 Then I put the object into a map and I do not access Employee object from Thread A anymore. 然后,将对象放入映射中,不再从线程A访问Employee对象。

Employee empl = new Employee("Jhon", 12000);
empl.setSalary(9000);
Map<String, Employee> employees = new ConcurrentHashMap<>();

And there is another Thread B, which constantly iterating over the map values in infinite loop and reading Employee salaries and other fields. 还有另一个线程B,它不断地在无限循环中遍历地图值并读取Employee薪水和其他字段。

Is there any chances that Thread B will see the salary used when the object has been constructed (12000), not the updated one? 线程B是否有可能看到构造对象时使用的薪水(12000),而不是更新的薪水? (9000) (9000)

Please note, I do not update the same object from the different threads at the same time. 请注意,我不会同时从不同线程更新同一对象。

Is there any chances that Thread B will see the salary used when the object has been constructed (12000), not the updated one? 线程B是否有可能看到构造对象时使用的薪水(12000),而不是更新的薪水? (9000) (9000)

Given: 鉴于:

  1. Employee employee = new Employee("John", 12000) in thread A Employee employee = new Employee("John", 12000)线程A中的Employee employee = new Employee("John", 12000)
  2. employee.setSalary(9000) in thread A 线程A中的employee.setSalary(9000)
  3. employees.put("someKey", employee) in thread A 线程A中的employees.put("someKey", employee)
  4. retrieving the employee from the employees map (map is a ConcurrentMap ) in thread B 从线程B中employees地图(地图是ConcurrentMap )中检索雇员
  5. employee.getSalary() in thread B 线程B中的 employee.getSalary()

thread B guaranteed to see only updated value (9000) 线程B确保仅看到更新的值(9000)


From ConcurrentMap 's javadoc : ConcurrentMap的javadoc

Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread. 内存一致性影响:与其他并发集合一样,在将对象作为键或值放入ConcurrentMap中之前,线程中的操作发生在从另一个线程中的ConcurrentMap中访问或删除该对象之后的操作之前

There is a happens-before relation between put ting an Employee into a ConcurrentMap and its subsequent retrieval by threadB . put Employee放入ConcurrentMap和随后由threadB进行检索之间存在先发生的关系。

It implies that there is also happens-before relation between setSalary action by thread A and getSalary by thread B. 这意味着线程A的setSalary操作与线程B的getSalary之间也存在事前关系。

So thread B will see 9000 因此线程B将看到9000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM