Will the value of a variable updated by one thread eventually seen by another thread if not synchronized in Java?

Yulin :

I know if the value of a variable is updated by one thread A and then read by another thread B, the new value may not be seen by thread B and B might get a stale value. My question is as computers are very fast, may I assume this possible latency issue is of the order of milliseconds and B will eventually see the new value if we are taking about time scales of say minutes or even hours?

Why I'm asking about this is in my code I have a map keeping some records and works as the following:

  1. user add a record to the map;

  2. user go do some work;

  3. user go back and remove the record;

A lot of users do this concurrently. Step 1 and step 3 is very fast and done in the same thread (the AKKA actor thread to be specific), step 2 takes time and is done in separate work threads. Now as step2 the work fails sometimes, step 3 may never get executed and forgotten records may accumulate in the map, I set a scheduler thread to check the map for forgotten records and remove them to avoid memory leakage, the check period is several hours as the failure happens very rarely, under this scenario, is it practically OK to use a non-concurrent map?

dm03514 :

If a single akka actor thread is responsible for the map access and the map is memory local to that actor, then it should not be necessary to use a concurrent map. This is because there is no concurrent access, and no chance of any race condition.

The issue is if the map is shared memory between the update/remove actor and the cleanup actor/thread. In this case it WOULD be necessary to synchronize or else there could be data races.

This could be avoided by the update/remove actor also supporting some sort of cleanup message (which will have performance/throughput implications for your actor but would be a simple and safe first approach), where it would block in order to iterate the map and cleanup orphaned records.


To answer your question it is NOT OK to use a non-concurrent (unsynchronized) map if the map is shared between multiple actors/threads.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328403&siteId=1