fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.time.DayOfWeek;
  4. import java.util.List;
  5. import java.util.Map;
  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. public static void main ( String[] args )
  12. {
  13. Ideone app = new Ideone();
  14. app.demo();
  15. }
  16.  
  17. private void demo ( )
  18. {
  19. ExecutorService executorService = Executors.newCachedThreadPool();
  20. Map < String, DayOfWeek > inputs =
  21. Map.of(
  22. "Alice" , DayOfWeek.MONDAY ,
  23. "Bob" , DayOfWeek.TUESDAY
  24. );
  25.  
  26. ConcurrentMap < String, DayOfWeek > map = new ConcurrentHashMap <>( inputs );
  27. System.out.println( "INFO - Before: map = " + map );
  28.  
  29. Repository repository = new Repository();
  30.  
  31. Callable < DayOfWeek > task = ( ) -> { return map.computeIfAbsent( "Carol" , ( String personNameKey ) -> {return repository.fetchDayOfWeekForPersonName( personNameKey ); } ); };
  32. List < Callable < DayOfWeek > > tasks = List.of( task , task , task , task , task );
  33. List < Future < DayOfWeek > > futures = List.of();
  34. try
  35. {
  36. futures = executorService.invokeAll( tasks );
  37. }
  38. {
  39. e.printStackTrace();
  40. }
  41.  
  42. executorService.shutdown();
  43. try { executorService.awaitTermination( 10 , TimeUnit.SECONDS ); } catch ( InterruptedException e ) { e.printStackTrace(); }
  44.  
  45. System.out.println( "INFO - After: map = " + map );
  46. futures.stream().forEach( dayOfWeekFuture -> {
  47. try
  48. {
  49. System.out.println( dayOfWeekFuture.get() );
  50. }
  51. {
  52. e.printStackTrace();
  53. }
  54. catch ( ExecutionException e )
  55. {
  56. e.printStackTrace();
  57. }
  58. } );
  59. }
  60.  
  61. class Repository
  62. {
  63. public DayOfWeek fetchDayOfWeekForPersonName ( final String personName )
  64. {
  65. return DayOfWeek.THURSDAY;
  66. }
  67. }
  68. }
  69.  
Success #stdin #stdout 0.11s 60340KB
stdin
Standard input is empty
stdout
INFO - Before: map = {Bob=TUESDAY, Alice=MONDAY}
INFO - After: map = {Bob=TUESDAY, Alice=MONDAY, Carol=THURSDAY}
THURSDAY
THURSDAY
THURSDAY
THURSDAY
THURSDAY