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 com.google.common.base.Stopwatch; 20 import com.google.common.base.Ticker; 21 import dagger.internal.Beta; 22 23 /** 24 * A monitor that measures the timing of the execution of a production component, and logs those 25 * timings with the given recorder. 26 * 27 * <p>This assumes that the given recorders do not throw or return null; for example, by using 28 * {@link TimingRecorders#delegatingProductionComponentTimingRecorderFactory}. 29 */ 30 // TODO(beder): Reduce the visibility of this class to package-private. 31 @Beta 32 public final class TimingProductionComponentMonitor extends ProductionComponentMonitor { 33 private final ProductionComponentTimingRecorder recorder; 34 private final Ticker ticker; 35 private final Stopwatch stopwatch; 36 TimingProductionComponentMonitor(ProductionComponentTimingRecorder recorder, Ticker ticker)37 TimingProductionComponentMonitor(ProductionComponentTimingRecorder recorder, Ticker ticker) { 38 this.recorder = recorder; 39 this.ticker = ticker; 40 this.stopwatch = Stopwatch.createStarted(ticker); 41 } 42 43 @Override producerMonitorFor(ProducerToken token)44 public ProducerMonitor producerMonitorFor(ProducerToken token) { 45 return new TimingProducerMonitor(recorder.producerTimingRecorderFor(token), ticker, stopwatch); 46 } 47 48 public static final class Factory extends ProductionComponentMonitor.Factory { 49 private final ProductionComponentTimingRecorder.Factory recorderFactory; 50 private final Ticker ticker; 51 Factory(ProductionComponentTimingRecorder.Factory recorderFactory)52 public Factory(ProductionComponentTimingRecorder.Factory recorderFactory) { 53 this(recorderFactory, Ticker.systemTicker()); 54 } 55 Factory(ProductionComponentTimingRecorder.Factory recorderFactory, Ticker ticker)56 Factory(ProductionComponentTimingRecorder.Factory recorderFactory, Ticker ticker) { 57 this.recorderFactory = recorderFactory; 58 this.ticker = ticker; 59 } 60 61 @Override create(Object component)62 public ProductionComponentMonitor create(Object component) { 63 return new TimingProductionComponentMonitor(recorderFactory.create(component), ticker); 64 } 65 } 66 } 67