1 package ch.hslu.exercises.sw08.ex2;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.concurrent.ExecutionException;
6 import java.util.concurrent.ExecutorService;
7 import java.util.concurrent.Executors;
8 import java.util.concurrent.Future;
9
10 import org.slf4j.LoggerFactory;
11 import org.slf4j.Logger;
12
13
14
15
16 public final class SpeedCount {
17
18 private static final Logger LOG = LoggerFactory.getLogger(SpeedCount.class);
19
20
21
22
23 private SpeedCount() {
24 }
25
26
27
28
29
30
31
32
33
34 public static long speedTest(Counter counter, int counts, int threads) throws ExecutionException, InterruptedException {
35 long duration;
36 long start;
37 long stop;
38 try (final ExecutorService executor = Executors.newCachedThreadPool()) {
39 start = System.currentTimeMillis();
40 List<Future<Integer>> futures = new ArrayList<>();
41 for (int i = 0; i < threads; i++) {
42 futures.add(executor.submit(new CountTask(counter, counts)));
43 }
44 for (Future<Integer> future : futures) {
45 future.get();
46 }
47 stop = System.currentTimeMillis();
48 }
49
50 duration = stop - start;
51
52
53 return duration;
54 }
55
56
57
58
59
60
61 public static void main(final String args[]) throws ExecutionException, InterruptedException {
62 final int passes = 10;
63 final int threads = Runtime.getRuntime().availableProcessors();
64 final int counts = 10_000;
65 final Counter counterSync = new SynchronizedCounter();
66 long sumSync = 0;
67
68
69 speedTest(counterSync, counts, threads);
70
71 for (int i = 0; i < passes; i++) {
72 sumSync += speedTest(counterSync, counts, threads);
73 }
74 final Counter counterAtom = new AtomicCounter();
75 long sumAtom = 0;
76 for (int i = 0; i < passes; i++) {
77 sumAtom += speedTest(counterAtom, counts, threads);
78 }
79
80 if (counterSync.get() == 0) {
81 LOG.info("Sync counter ok");
82 LOG.info("Sync counter average test duration = {} ms", sumSync / (float) passes);
83 } else {
84 LOG.info("Sync counter failed");
85 }
86 if (counterAtom.get() == 0) {
87 LOG.info("Atom counter ok");
88 LOG.info("Atom counter average test duration = {} ms", sumAtom / (float) passes);
89 } else {
90 LOG.info("Atom counter failed");
91 }
92 }
93 }