Bug 9060: Minor [Java|inline] doc update re. getStackTrace() performance
[controller.git] / opendaylight / md-sal / mdsal-trace / dom-impl / src / main / java / org / opendaylight / controller / md / sal / trace / closetracker / impl / CloseTrackedTrait.java
1 /*
2  * Copyright (c) 2017 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.md.sal.trace.closetracker.impl;
9
10 import java.util.Objects;
11 import javax.annotation.Nullable;
12
13 /**
14  * Implementation of {@link CloseTracked} which can be used as a field in
15  * another class which implements {@link CloseTracked} and delegates its methods
16  * to this.
17  *
18  * <p>This is useful if that class already has another parent class.
19  * If it does not, then it's typically more convenient to just extend AbstractCloseTracked.
20  *
21  * @author Michael Vorburger.ch
22  */
23 public class CloseTrackedTrait<T extends CloseTracked<T>> implements CloseTracked<T> {
24
25     // NB: It's important that we keep a Throwable here, and not directly the StackTraceElement[] !
26     // This is because creating a new Throwable() is a lot less expensive in terms of runtime overhead
27     // than actually calling its getStackTrace(), which we can delay until we really need to.
28     // see also e.g. https://stackoverflow.com/a/26122232/421602
29     private final @Nullable Throwable allocationContext;
30     private final CloseTrackedRegistry<T> closeTrackedRegistry;
31     private final CloseTracked<T> realCloseTracked;
32
33     public CloseTrackedTrait(CloseTrackedRegistry<T> transactionChainRegistry, CloseTracked<T> realCloseTracked) {
34         if (transactionChainRegistry.isDebugContextEnabled()) {
35             // NB: We're NOT doing the (expensive) getStackTrace() here just yet (only below)
36             // TODO When we're on Java 9, then instead use the new java.lang.StackWalker API..
37             this.allocationContext = new Throwable();
38         } else {
39             this.allocationContext = null;
40         }
41         this.realCloseTracked = Objects.requireNonNull(realCloseTracked, "realCloseTracked");
42         this.closeTrackedRegistry = Objects.requireNonNull(transactionChainRegistry, "transactionChainRegistry");
43         this.closeTrackedRegistry.add(this);
44     }
45
46     @Override
47     @Nullable
48     public StackTraceElement[] getAllocationContextStackTrace() {
49         return allocationContext != null ? allocationContext.getStackTrace() : null;
50     }
51
52     public void removeFromTrackedRegistry() {
53         closeTrackedRegistry.remove(this);
54     }
55
56     @Override
57     public CloseTracked<T> getRealCloseTracked() {
58         return realCloseTracked;
59     }
60
61 }