• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package dagger.producers.monitoring;
18 
19 import static java.util.concurrent.TimeUnit.NANOSECONDS;
20 
21 import com.google.common.base.Stopwatch;
22 import com.google.common.base.Ticker;
23 
24 /**
25  * A monitor that measures the timing of the execution of a producer method, and logs those timings
26  * with the given recorder.
27  */
28 @SuppressWarnings("GoodTime") // should use java.time.Duration
29 final class TimingProducerMonitor extends ProducerMonitor {
30   private final ProducerTimingRecorder recorder;
31   private final Stopwatch stopwatch;
32   private final Stopwatch componentStopwatch;
33   private long startNanos = -1;
34 
TimingProducerMonitor( ProducerTimingRecorder recorder, Ticker ticker, Stopwatch componentStopwatch)35   TimingProducerMonitor(
36       ProducerTimingRecorder recorder, Ticker ticker, Stopwatch componentStopwatch) {
37     this.recorder = recorder;
38     this.stopwatch = Stopwatch.createUnstarted(ticker);
39     this.componentStopwatch = componentStopwatch;
40   }
41 
42   @Override
methodStarting()43   public void methodStarting() {
44     startNanos = componentStopwatch.elapsed(NANOSECONDS);
45     stopwatch.start();
46   }
47 
48   @Override
methodFinished()49   public void methodFinished() {
50     // TODO(beder): Is a system ticker the appropriate way to track CPU time? Should we use
51     // ThreadCpuTicker instead?
52     long durationNanos = stopwatch.elapsed(NANOSECONDS);
53     recorder.recordMethod(startNanos, durationNanos);
54   }
55 
56   @Override
succeeded(Object o)57   public void succeeded(Object o) {
58     long latencyNanos = stopwatch.elapsed(NANOSECONDS);
59     recorder.recordSuccess(latencyNanos);
60   }
61 
62   @Override
failed(Throwable t)63   public void failed(Throwable t) {
64     if (stopwatch.isRunning()) {
65       long latencyNanos = stopwatch.elapsed(NANOSECONDS);
66       recorder.recordFailure(t, latencyNanos);
67     } else {
68       recorder.recordSkip(t);
69     }
70   }
71 }
72