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