Java ConcurrentHashMap add key value pair if absent

Description

Java ConcurrentHashMap add key value pair if absent

import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class Main {
   Random random = new Random();
   Set<Thread> updateThreads = new HashSet<Thread>();

   public static void main(String[] args) {
      new Main().start();
   }//from  w  ww  .  j ava 2s .  c  o m
   private void start() {
      ConcurrentMap<Integer, String> concurrentMap = new ConcurrentHashMap<Integer, String>();
      for (int i = 0; i < 100; i++) {
         startUpdateThread(i, concurrentMap);
      }
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
      for (Map.Entry<Integer, String> entry : concurrentMap.entrySet()) {
         System.out.println("Key :" + entry.getKey() + " Value:" + entry.getValue());
      }
   }
   private void startUpdateThread(final int i, final ConcurrentMap<Integer, String> concurrentMap) {
      Thread thread = new Thread(new Runnable() {
         public void run() {
            int randomInt = random.nextInt(20);
            String previousEntry = concurrentMap.putIfAbsent(randomInt, "Thread # " + i + " has made it!");
            if (previousEntry != null) {
               System.out.println("Thread # " + i + " tried to update it but guess what, we're too late!");
               return;
            } else {
               System.out.println("Thread # " + i + " has made it!");
               return;

            }
         }
      });
      thread.start();
   }

}



PreviousNext

Related