Ihor M.
Ihor M.

Reputation: 3148

What happens if an object is modified outside of the concurrent map in java?

What happens if an object is modified outside of the concurrent map in java?

Say, I have a concurrent hash map and in one thread I retrieve a value from that map and modify its state. Will the other threads see the modification without an additional synchronization?

Upvotes: 0

Views: 1180

Answers (2)

Andy Turner
Andy Turner

Reputation: 140319

The key concept in the Java Memory Model is the happens before relation. You can only rely on things happening between threads if there is a happens before relationship between the two of them.

In the case of ConcurrentHashMap, there is a happens-before relationship between a put and a subsequent get of the value for the same key: updating the value and putting it into the map happens before getting the value and reading its state. Because of that happens before relationship, the update happens before the reading of the state, so you will see the updated state.

So, if you update the state of an object, and then put it into the map, if you subsequently get it from the map, you are guaranteed to see that updated state (until such time as you put again).

But, if you have a reference to that object outside the context of a ConcurrentHashMap, there is no automatic happens-before relationship. You have to create that relationship for yourself.

One way of doing this is with synchronization (as in using synchronized, on the same object in all threads); other ways include:

  • writing and reading a volatile variable
  • using a Lock
  • putting the object into the map again, and then getting from the map before you start using it in the other thread.

Upvotes: 4

Burak Serdar
Burak Serdar

Reputation: 51542

Short answer is no.

A concurrent map will only synchronize the access to the map. That is, if one thread writes the map, all other threads can see that without additional synchronization.

If you retrieve an object from the map and modify it without synchronization, and if another thread retrieves the same object to read it, then you have a race without explicit synchronization between those threads.

Upvotes: 2

Related Questions