View Javadoc
1   package examples.example2;
2   
3   import java.io.IOException;
4   
5   import java.util.ArrayList;
6   import java.util.List;
7   import java.util.concurrent.ExecutionException;
8   import java.util.concurrent.ExecutorService;
9   import java.util.concurrent.Executors;
10  import java.util.concurrent.Future;
11  import java.util.concurrent.TimeUnit;
12  import java.util.concurrent.atomic.AtomicInteger;
13  
14  import examples.example2.classes.MyCaller;
15  
16  
17  public class Simulation {
18    public static void main(String[] args) throws ExecutionException, InterruptedException {
19      MyCaller myCaller = new MyCaller();
20  
21      // simulate access by 10 threads
22  
23      ExecutorService executorService = Executors.newWorkStealingPool(10);
24      List<Future> responses = new ArrayList<>();
25  
26      // simulate multiple execution of the method by different threads
27      long start = System.currentTimeMillis();
28  
29      for (int i = 0; i < 100; i++) {
30        AtomicInteger pingId = new AtomicInteger(i);
31  
32        executorService.submit(() -> {
33          try {
34            myCaller.ping(pingId.get());
35          } catch (IOException e) {
36            System.out.println("Exception while handling ping #" + pingId.get());
37          }
38        });
39      }
40  
41  
42      executorService.shutdown();
43      executorService.awaitTermination(2, TimeUnit.MINUTES);
44  
45      long stop = System.currentTimeMillis();
46      System.out.printf("Finished in %d seconds", (int) (stop - start) / 1000);
47  
48    }
49  
50  }