fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.concurrent.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. static ConcurrentMap<String, List<Integer>> map = new ConcurrentHashMap<>();
  12.  
  13. static void safeAdd(String key, Integer val) {
  14. map.compute(key, (k, list) -> {
  15. sleepSilently(2000);
  16. if (list == null) {
  17. list = new ArrayList<>();
  18. }
  19. list.add(val);
  20. return list;
  21. });
  22. }
  23.  
  24. static List<Integer> safeGet(String key) {
  25. List<Integer> list = map.compute(key, (k, l) -> l);
  26. return list != null ? Collections.unmodifiableList(list) : null;
  27. }
  28.  
  29. public static void main(String[] args) {
  30. map.put("A", new ArrayList<>(Arrays.asList(1, 2, 3)));
  31. map.put("B", new ArrayList<>(Arrays.asList(1, 2, 3)));
  32.  
  33. new Thread(() -> {
  34. System.out.println("begin add to A");
  35. safeAdd("A", 4);
  36. System.out.println("finish add A");
  37. }).start();
  38. new Thread(() -> {
  39. sleepSilently(1000);
  40. System.out.println("begin get A");
  41. System.out.println("A= " + safeGet("A"));
  42. }).start();
  43. new Thread(() -> {
  44. sleepSilently(1300);
  45. System.out.println("get A unsafely= " + map.get("A"));
  46. }).start();
  47. new Thread(() -> {
  48. sleepSilently(1600);
  49. System.out.println("begin get B");
  50. System.out.println("B= " + safeGet("B"));
  51. }).start();
  52. }
  53.  
  54. static void sleepSilently(long millis) {
  55. try {
  56. Thread.sleep(millis);
  57. } catch (InterruptedException e) {
  58. // ignore
  59. }
  60. }
  61. }
Success #stdin #stdout 0.12s 60532KB
stdin
Standard input is empty
stdout
begin add to A
begin get A
get A unsafely= [1, 2, 3]
begin get B
B= [1, 2, 3]
finish add A
A= [1, 2, 3, 4]