Java ConcurrentHashMap update and iterate

Description

Java ConcurrentHashMap update and iterate

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

public class Main {
   Set<Thread> updateThreads = new HashSet<Thread>();
   Random random = new Random();
   /* www . j av  a2 s.c  o  m*/
   private void start() {
      ConcurrentMap<Integer, String> concurrentMap = new ConcurrentHashMap<Integer, String>();
      for (int i = 0; i < 1000; 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());
      }
      for (Thread thread : updateThreads) {
         thread.interrupt();
      }
   }
   private void startUpdateThread(int i, final ConcurrentMap<Integer, String> concurrentMap) {
      Thread thread = new Thread(new Runnable() {
         public void run() {
            while (!Thread.interrupted()) {
               int randomInt = random.nextInt(20);
               concurrentMap.put(randomInt, UUID.randomUUID().toString());
            }
         }
      });
      thread.setName("Update Thread " + i);
      updateThreads.add(thread);
      thread.start();
   }
   public static void main(String[] args) {
      new Main().start();   
   }   
}



PreviousNext

Related