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.

2
  • 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 question. Commented Jul 21, 2019 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. Commented Jul 21, 2019 at 19:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.