Search code examples
javamultidimensional-arraysynchronizationhappens-before

Establishing Happens-Before in Arrays


Have a quick synchronization question, here is what I have:

a) Class1 has a concurrent hash map defined as follows:

ConcurrentMap<String, int[][]> map  = new ConcurrentHashMap<String, int[][]>();

b) Class2 has a thread, called Thread1. Thread1 creates an Id and checks if map contains it. If it does, it retrieves the value (int[][]), modifies the contents and puts it back. If it doesn't, it creates a new int[][] and stores it. This process of check->modify/create happens frequently.

 private class Thread1 implements Runnable{

            public void run(){
                //keepRunning is volatile
                while( keepRunning ){

                  String id     = "ItemA";
                  int[][] value = map.get(id);

                  //If value is null, create an int[][] and put it back as value for Id
                  //If value is not null, modify the contents according to some logic  
                 }
             }
    }

c) Finally, I have another thread, called Thread2. This thread takes an id, checks if the map has a value for it. If it doesn't, nothing happens. If it does, then it sums up the values in int[][] and uses the number for some calculation (no modifications here).

I am trying to figure out if my operations are atomic. Operations in b) are fine as the creation/modification of the array and insertion into the map is confined to only one thread (Thread1).

Also, since insertion into the map establishes a happens-before action, this will ensure that c) will see the updated values in int[][].

However, I am not too sure of what would happen if Thread2 looks up the same int[][] in the map and tries to sum it up while Thread1 is modifying it.

Am I correct in thinking that Thread2 will see the older (but uncorrupted) values in int[][]. Reason being that until Thread1 has finished putting the value back into the map, the new modifications wont be visible to Thread2.

Thanks very much.


Solution

  • Your operations are not atomic, thread 2 will be trying to sum the values while thread 1 is modifying them.

    To avoid that you'll need to duplicate the original modify the duplicate and put back the copy.