Java - Collection Framework Concurrent Maps

Introduction

You should use a ConcurrentMap in a multi-threaded environment.

ConcurrentMap does not lock the entire map.

ConcurrentHashMap class implements the ConcurrentMap interface.

Both of them are in the java.util.concurrent package.

The following code creates and uses some of the methods of a ConcurrentMap.

Demo

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class Main {
  public static void main(String[] args) {
    ConcurrentMap<String, String> cMap = new ConcurrentHashMap<>();
    cMap.put("one", "one");

    System.out.println("Concurrent Map: " + cMap);
    System.out.println(cMap.putIfAbsent("one", "nine"));
    System.out.println(cMap.putIfAbsent("two", "two"));
    System.out.println(cMap.remove("one", "two"));
    System.out.println(cMap.replace("one", "two"));

    System.out.println("Concurrent Map: " + cMap);
  }/*from  www.  j av  a 2s  .  com*/
}

Result