Inserting a Key into a Map Only If the Key Is Not Already Present - Java Thread

Java examples for Thread:Concurrent Map

Description

Inserting a Key into a Map Only If the Key Is Not Already Present

Demo Code

import java.util.HashSet;
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<>();

  public static void main(String[] args) {
    Main recipe = new Main();
    recipe.startProcess();// ww w  . j  av a  2  s.  c  o  m
  }

  private void startProcess() {
    ConcurrentMap<Integer, String> concurrentMap = new ConcurrentHashMap<>();
    for (int i = 0; i < 100; i++) {
      startUpdateThread(i, concurrentMap);
    }

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    concurrentMap
        .entrySet()
        .stream()
        .forEach(
            (entry) -> {
              System.out.println("Key :" + entry.getKey() + " Value:"
                  + entry.getValue());
            });

  }

  private void startUpdateThread(final int i,
      final ConcurrentMap<Integer, String> concurrentMap) {
    Thread thread = new Thread(() -> {
      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!");
      } else {
        System.out.println("Thread # " + i + " has made it!");
      }
    });
    thread.start();
  }

}

Result


Related Tutorials