/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	static ConcurrentMap<String, List<Integer>> map = new ConcurrentHashMap<>();

    static void safeAdd(String key, Integer val) {
        map.compute(key, (k, list) -> {
            sleepSilently(2000);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(val);
            return list;
        });
    }

    static List<Integer> safeGet(String key) {
        List<Integer> list = map.compute(key, (k, l) -> l);
        return list != null ? Collections.unmodifiableList(list) : null;
    }

    public static void main(String[] args) {
        map.put("A", new ArrayList<>(Arrays.asList(1, 2, 3)));
        map.put("B", new ArrayList<>(Arrays.asList(1, 2, 3)));

        new Thread(() -> {
            System.out.println("begin add to A");
            safeAdd("A", 4);
            System.out.println("finish add A");
        }).start();
        new Thread(() -> {
            sleepSilently(1000);
            System.out.println("begin get A");
            System.out.println("A= " + safeGet("A"));
        }).start();
        new Thread(() -> {
            sleepSilently(1300);
            System.out.println("get A unsafely= " + map.get("A"));
        }).start();
        new Thread(() -> {
            sleepSilently(1600);
            System.out.println("begin get B");
            System.out.println("B= " + safeGet("B"));
        }).start();
    }

    static void sleepSilently(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            // ignore
        }
    }
}