Search code examples
javamultithreadingconcurrencyjava-threads

Concurrent access of List of Map in Java


I have the following List.

 List<Map<String,String>> input = new ArrayList<Map<String,String>>();

I have a requirement where each Map object in List is accessed in threads. It is guarenteed no two threads access the same map object.

for(Map<String,String> input : inputList){
    triggerThread(input); // Thread modifies the input. It adds elements in the input map
}

Do I need to use synchronizedList(inputList) or synchronizedmap(input) or is it OK to use input map directly without any synchronization logic? Which is the good design?

This might be the basic question. I am quite confused on how to implement.

   class Main{
      public static void main(String[] args){
       List<Map<String,String>> inputList = new ArrayList<Map<String,String>>();
       Map<String,String> input = new HashMap<String,String>();
       input.put("attr1","param1");
       inputList.add(input);
       ExecutorService pool= Executors.newFixedThreadPool(10);
       for(Map<String,String> input : inputList){
         RequestHandler request = new RequestHandler(input);
         pool.submit(request);
        }
      }
   }

     class RequestHandler extends Runnable{
         Map<String,String> input;
         RequestHandler(Map<String,String> input){
           this.input=input;
         }
        @Override
         public void run() {
           //writing logic vaguely
           input.add("attr2", "param2");
        }
    }

Solution

  • Assuming the following:

    • The inputList list is populated by one thread, and then it is not modified (i.e. no elements are added/removed) by other threads
    • No two threads access the same map object in the input map (as the question states)

    If this is the case, then there is no need to synchronize on inputList nor on input.

    If, on the other hand, you will access inputList itself by other threads, use Collections.syncrhonizedList() for example.