f69134f391c9b0803dffdb0480a6f5d98f6eeeac
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / RecursiveObjectLeaker.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, 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.yangtools.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.ArrayDeque;
14 import java.util.Deque;
15 import java.util.Map.Entry;
16 import javax.annotation.Nullable;
17 import javax.annotation.concurrent.ThreadSafe;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * Thread-local hack to make recursive extensions work without too much hassle. The idea is that prior to instantiating
23  * an extension, the definition object checks whether it is already present on the stack, recorded object is returned.
24  *
25  * <p>
26  * If it is not, it will push itself to the stack as unresolved and invoke the constructor. The constructor's lowermost
27  * class calls to this class and if the topmost entry is not resolved, it will leak itself.
28  *
29  * <p>
30  * Upon return from the constructor, the topmost entry is removed and if the queue is empty, the thread-local variable
31  * will be cleaned up.
32  *
33  * <p>
34  * WARNING: BE CAREFUL WHEN USING THIS CLASS. IT LEAKS OBJECTS WHICH ARE NOT COMPLETELY INITIALIZED.
35  *
36  * <p>
37  * WARNING: THIS CLASS EAVES THREAD-LOCAL RESIDUE. MAKE SURE IT IS OKAY OR CALL {@link #cleanup()} IN APPROPRIATE
38  *          PLACES.
39  *
40  * <p>
41  * THIS CLASS IS EXTREMELY DANGEROUS (okay, not as much as sun.misc.unsafe). YOU HAVE BEEN WARNED. IF SOMETHING BREAKS
42  * IT IS PROBABLY YOUR FAULT AND YOU ARE ON YOUR OWN.
43  *
44  * @author Robert Varga
45  */
46 @Beta
47 @ThreadSafe
48 public final class RecursiveObjectLeaker {
49     // Logging note. Only keys passed can be logged, as objects beng resolved may not be properly constructed.
50     private static final Logger LOG = LoggerFactory.getLogger(RecursiveObjectLeaker.class);
51
52     // Initial value is set to null on purpose, so we do not allocate anything (aside the map)
53     private static final ThreadLocal<Deque<Entry<?, Object>>> STACK = new ThreadLocal<>();
54
55     private RecursiveObjectLeaker() {
56         throw new UnsupportedOperationException();
57     }
58
59     // Key is checked for identity
60     public static void beforeConstructor(final Object key) {
61         Deque<Entry<?, Object>> stack = STACK.get();
62         if (stack == null) {
63             // Biased: this class is expected to be rarely and shallowly used
64             stack = new ArrayDeque<>(1);
65             STACK.set(stack);
66         }
67
68         LOG.debug("Resolving key {}", key);
69         stack.push(new SimpleEntry<>(key, null));
70     }
71
72     // Can potentially store a 'null' mapping. Make sure cleanup() is called
73     public static void inConstructor(final Object obj) {
74         final Deque<Entry<?, Object>> stack = STACK.get();
75         if (stack != null) {
76             final Entry<?, Object> top = stack.peek();
77             if (top != null) {
78                 if (top.getValue() == null) {
79                     LOG.debug("Resolved key {}", top.getKey());
80                     top.setValue(obj);
81                 }
82             } else {
83                 LOG.info("Cleaned stale empty stack", new Exception());
84                 STACK.set(null);
85             }
86         } else {
87             LOG.trace("No thread stack");
88         }
89     }
90
91     // Make sure to call this from a finally block
92     public static void afterConstructor(final Object key) {
93         final Deque<Entry<?, Object>> stack = STACK.get();
94         Preconditions.checkState(stack != null, "No stack allocated when completing %s", key);
95
96         final Entry<?, Object> top = stack.pop();
97         if (stack.isEmpty()) {
98             LOG.trace("Removed empty thread stack");
99             STACK.set(null);
100         }
101
102         Preconditions.checkState(key == top.getKey(), "Expected key %s, have %s", top.getKey(), key);
103         Preconditions.checkState(top.getValue() != null, "");
104     }
105
106     // BEWARE: this method returns incpmpletely-initialized objects (that is the purpose of this class).
107     //
108     //         BE VERY CAREFUL WHAT OBJECT STATE YOU TOUCH
109     public static @Nullable <T> T lookup(final Object key, final Class<T> requiredClass) {
110         final Deque<Entry<?, Object>> stack = STACK.get();
111         if (stack != null) {
112             for (Entry<?, Object> e : stack) {
113                 // Keys are treated as identities
114                 if (key == e.getKey()) {
115                     Preconditions.checkState(e.getValue() != null, "Object for %s is not resolved", key);
116                     LOG.debug("Looked up key {}", e.getKey());
117                     return requiredClass.cast(e.getValue());
118                 }
119             }
120         }
121
122         return null;
123     }
124
125     // Be sure to call this in from a finally block when bulk processing is done, so that this class can be unloaded
126     public static void cleanup() {
127         STACK.remove();
128         LOG.debug("Removed thread state");
129     }
130 }