1

I've created an Employee Object in Thread A. An Employee class is mutable . In the same thread A, I've updated employee salary and change other fields. Then I put the object into a map and I do not access Employee object from Thread A anymore.

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.

Is there any chances that Thread B will see the salary used when the object has been constructed (12000), not the updated one? (9000)

Please note, I do not update the same object from the different threads at the same time.

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53
user12384512
  • 3,362
  • 10
  • 61
  • 97
  • You are using `ConcurentHashMap` already so as long as you do not modify/read the object in Thread A after putting it - it should be fine. Also you can look at [this](https://stackoverflow.com/questions/3768554/is-iterating-concurrenthashmap-values-thread-safe) question. – Michał Krzywański Jul 21 '19 at 19:28
  • 3
    When you put the object in the shared map ( I assume that you create this object in some method so it is a local object confined to this Thread) you publish it's state, so as long as you do not modify/read it after putting - there is nothing to worry about. If you wanted to modify it after putting it there - then you would have a problem and would have to synchronize on some common lock when accessing this object. – Michał Krzywański Jul 21 '19 at 19:38

1 Answers1

2

Is there any chances that Thread B will see the salary used when the object has been constructed (12000), not the updated one? (9000)

Given:

  1. Employee employee = new Employee("John", 12000) in thread A
  2. employee.setSalary(9000) in thread A
  3. employees.put("someKey", employee) in thread A
  4. retrieving the employee from the employees map (map is a ConcurrentMap) in thread B
  5. employee.getSalary() in thread B

thread B guaranteed to see only updated value (9000)


From ConcurrentMap's 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.

There is a happens-before relation between putting an Employee into a ConcurrentMap and its subsequent retrieval by threadB.

It implies that there is also happens-before relation between setSalary action by thread A and getSalary by thread B.

So thread B will see 9000

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53