View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.monitoring.stopwatches;
18  
19  import org.apache.commons.monitoring.counters.Counter;
20  
21  import java.util.concurrent.atomic.AtomicInteger;
22  
23  import static org.apache.commons.monitoring.counters.Unit.Time.NANOSECOND;
24  
25  public class CounterStopWatch implements StopWatch {
26      protected final Counter counter;
27      protected final long startedAt;
28      protected final AtomicInteger concurrencyCounter;
29      protected long stopedAt;
30      protected boolean stoped;
31  
32      public CounterStopWatch(final Counter counter) {
33          this.counter = counter;
34          startedAt = nanotime();
35  
36          concurrencyCounter = counter.currentConcurrency();
37          final int concurrency = concurrencyCounter.incrementAndGet();
38          counter.updateConcurrency(concurrency);
39      }
40  
41      protected long nanotime() {
42          return System.nanoTime();
43      }
44  
45      @Override
46      public long getElapsedTime() {
47          if (!stoped) {
48              return nanotime() - startedAt;
49          }
50          return stopedAt - startedAt;
51      }
52  
53      @Override
54      public StopWatch stop() {
55          if (!stoped) {
56              stopedAt = nanotime();
57              stoped = true;
58              doStop();
59          }
60          return this;
61      }
62  
63      protected void doStop() {
64          counter.add(getElapsedTime(), NANOSECOND);
65          concurrencyCounter.decrementAndGet();
66      }
67  
68      @Override
69      public String toString() {
70          final StringBuilder stb = new StringBuilder();
71          if (counter != null) {
72              stb.append("Execution for ").append(counter.getKey().toString()).append(" ");
73          }
74          if (stoped) {
75              stb.append("stoped after ").append(getElapsedTime()).append("ns");
76          } else {
77              stb.append("running for ").append(getElapsedTime()).append("ns");
78          }
79          return stb.toString();
80  
81      }
82  }