1 package org.djutils.stats.summarizers;
2
3 import org.djutils.exceptions.Throw;
4
5
6
7
8
9
10
11
12
13
14
15
16 public class Counter implements Statistic
17 {
18
19 private static final long serialVersionUID = 20200228L;
20
21
22 private long count = 0;
23
24
25 private long n = 0;
26
27
28 private String description;
29
30
31 private Object semaphore = new Object();
32
33
34
35
36
37 public Counter(final String description)
38 {
39 Throw.whenNull(description, "description cannot be null");
40 this.description = description;
41 initialize();
42 }
43
44
45
46
47
48 public long getCount()
49 {
50 return this.count;
51 }
52
53
54 @Override
55 public long getN()
56 {
57 return this.n;
58 }
59
60
61
62
63
64
65 public long register(final long value)
66 {
67 synchronized (this.semaphore)
68 {
69 this.count += value;
70 this.n++;
71 }
72 return value;
73 }
74
75
76
77
78 @Override
79 public void initialize()
80 {
81 synchronized (this.semaphore)
82 {
83 this.n = 0;
84 this.count = 0;
85 }
86 }
87
88
89 @Override
90 public String getDescription()
91 {
92 return this.description;
93 }
94
95
96
97
98
99 public static String reportHeader()
100 {
101 return "-".repeat(72) + String.format("%n| %-48.48s | %6.6s | %8.8s |%n", "Counter name", "n", "count")
102 + "-".repeat(72);
103 }
104
105
106 @Override
107 public String reportLine()
108 {
109 return String.format("| %-48.48s | %6d | %8d |", getDescription(), getN(), getCount());
110 }
111
112
113
114
115
116 public static String reportFooter()
117 {
118 return "-".repeat(72);
119 }
120
121
122 @Override
123 public String toString()
124 {
125 return "Counter [description=" + this.description + ", n=" + this.n + ", count=" + this.count + "]";
126 }
127
128 }