| 30 | */ |
| 31 | // TODO(beder): Reduce the visibility of this class to package-private. |
| 32 | @Beta |
| 33 | public final class TimingRecorders { |
| 34 | private static final Logger logger = Logger.getLogger(TimingRecorders.class.getName()); |
| 35 | |
| 36 | /** |
| 37 | * Returns a timing recorder factory that delegates to the given factories, and ensures that any |
| 38 | * method called on this object, even transitively, does not throw a {@link RuntimeException} or |
| 39 | * return null. |
| 40 | * |
| 41 | * <p>If the delegate recorders throw an {@link Error}, then that will escape this recorder |
| 42 | * implementation. Errors are treated as unrecoverable conditions, and may cause the entire |
| 43 | * component's execution to fail. |
| 44 | */ |
| 45 | public static ProductionComponentTimingRecorder.Factory |
| 46 | delegatingProductionComponentTimingRecorderFactory( |
| 47 | Collection<ProductionComponentTimingRecorder.Factory> factories) { |
| 48 | switch (factories.size()) { |
| 49 | case 0: |
| 50 | return noOpProductionComponentTimingRecorderFactory(); |
| 51 | case 1: |
| 52 | return new NonThrowingProductionComponentTimingRecorder.Factory( |
| 53 | Iterables.getOnlyElement(factories)); |
| 54 | default: |
| 55 | return new DelegatingProductionComponentTimingRecorder.Factory(factories); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * A component recorder that delegates to a single recorder, and catches and logs all exceptions |
| 61 | * that the delegate throws. |
| 62 | */ |
| 63 | private static final class NonThrowingProductionComponentTimingRecorder |
| 64 | implements ProductionComponentTimingRecorder { |
| 65 | private final ProductionComponentTimingRecorder delegate; |
| 66 | |
| 67 | NonThrowingProductionComponentTimingRecorder(ProductionComponentTimingRecorder delegate) { |
| 68 | this.delegate = delegate; |
| 69 | } |
| 70 | |
| 71 | @Override |
| 72 | public ProducerTimingRecorder producerTimingRecorderFor(ProducerToken token) { |
| 73 | try { |
| 74 | ProducerTimingRecorder recorder = delegate.producerTimingRecorderFor(token); |
| 75 | return recorder == null |
| 76 | ? ProducerTimingRecorder.noOp() |
| 77 | : new NonThrowingProducerTimingRecorder(recorder); |
| 78 | } catch (RuntimeException e) { |
| 79 | logProducerTimingRecorderForException(e, delegate, token); |
| 80 | return ProducerTimingRecorder.noOp(); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | static final class Factory implements ProductionComponentTimingRecorder.Factory { |
| 85 | private final ProductionComponentTimingRecorder.Factory delegate; |
| 86 | |
| 87 | Factory(ProductionComponentTimingRecorder.Factory delegate) { |
| 88 | this.delegate = delegate; |
| 89 | } |