View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util.concurrent;
17  
18  import io.netty.util.internal.InternalThreadLocalMap;
19  import io.netty.util.internal.PlatformDependent;
20  
21  import java.util.Collections;
22  import java.util.IdentityHashMap;
23  import java.util.Set;
24  
25  /**
26   * A special variant of {@link ThreadLocal} that yields higher access performance when accessed from a
27   * {@link FastThreadLocalThread}.
28   * <p>
29   * Internally, a {@link FastThreadLocal} uses a constant index in an array, instead of using hash code and hash table,
30   * to look for a variable.  Although seemingly very subtle, it yields slight performance advantage over using a hash
31   * table, and it is useful when accessed frequently.
32   * </p><p>
33   * To take advantage of this thread-local variable, your thread must implement {@link FastThreadLocalAccess}.
34   * By default, all threads created by {@link DefaultThreadFactory} and {@link DefaultExecutorServiceFactory} implement
35   * {@link FastThreadLocalAccess}.
36   * </p><p>
37   * Note that the fast path is only possible on threads that implement {@link FastThreadLocalAccess}, because it
38   * requires a special field to store the necessary state. An access by any other kind of thread falls back to a regular
39   * {@link ThreadLocal}.
40   * </p>
41   *
42   * @param <V> the type of the thread-local variable
43   * @see ThreadLocal
44   */
45  public class FastThreadLocal<V> {
46  
47      private static final int variablesToRemoveIndex = InternalThreadLocalMap.nextVariableIndex();
48  
49      /**
50       * Removes all {@link FastThreadLocal} variables bound to the current thread.  This operation is useful when you
51       * are in a container environment, and you don't want to leave the thread local variables in the threads you do not
52       * manage.
53       */
54      public static void removeAll() {
55          InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet();
56          if (threadLocalMap == null) {
57              return;
58          }
59  
60          try {
61              Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
62              if (v != null && v != InternalThreadLocalMap.UNSET) {
63                  @SuppressWarnings("unchecked")
64                  Set<FastThreadLocal<?>> variablesToRemove = (Set<FastThreadLocal<?>>) v;
65                  FastThreadLocal<?>[] variablesToRemoveArray =
66                          variablesToRemove.toArray(new FastThreadLocal[variablesToRemove.size()]);
67                  for (FastThreadLocal<?> tlv: variablesToRemoveArray) {
68                      tlv.remove(threadLocalMap);
69                  }
70              }
71          } finally {
72              InternalThreadLocalMap.remove();
73          }
74      }
75  
76      /**
77       * Returns the number of thread local variables bound to the current thread.
78       */
79      public static int size() {
80          InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet();
81          if (threadLocalMap == null) {
82              return 0;
83          } else {
84              return threadLocalMap.size();
85          }
86      }
87  
88      /**
89       * Destroys the data structure that keeps all {@link FastThreadLocal} variables accessed from
90       * non-{@link FastThreadLocalThread}s.  This operation is useful when you are in a container environment, and you
91       * do not want to leave the thread local variables in the threads you do not manage.  Call this method when your
92       * application is being unloaded from the container.
93       */
94      public static void destroy() {
95          InternalThreadLocalMap.destroy();
96      }
97  
98      @SuppressWarnings("unchecked")
99      private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, FastThreadLocal<?> variable) {
100         Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
101         Set<FastThreadLocal<?>> variablesToRemove;
102         if (v == InternalThreadLocalMap.UNSET || v == null) {
103             variablesToRemove = Collections.newSetFromMap(new IdentityHashMap<FastThreadLocal<?>, Boolean>());
104             threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove);
105         } else {
106             variablesToRemove = (Set<FastThreadLocal<?>>) v;
107         }
108 
109         variablesToRemove.add(variable);
110     }
111 
112     private static void removeFromVariablesToRemove(
113             InternalThreadLocalMap threadLocalMap, FastThreadLocal<?> variable) {
114 
115         Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
116 
117         if (v == InternalThreadLocalMap.UNSET || v == null) {
118             return;
119         }
120 
121         @SuppressWarnings("unchecked")
122         Set<FastThreadLocal<?>> variablesToRemove = (Set<FastThreadLocal<?>>) v;
123         variablesToRemove.remove(variable);
124     }
125 
126     private final int index;
127 
128     public FastThreadLocal() {
129         index = InternalThreadLocalMap.nextVariableIndex();
130     }
131 
132     /**
133      * Returns the current value for the current thread
134      */
135     public final V get() {
136         return get(InternalThreadLocalMap.get());
137     }
138 
139     /**
140      * Returns the current value for the specified thread local map.
141      * The specified thread local map must be for the current thread.
142      */
143     @SuppressWarnings("unchecked")
144     public final V get(InternalThreadLocalMap threadLocalMap) {
145         Object v = threadLocalMap.indexedVariable(index);
146         if (v != InternalThreadLocalMap.UNSET) {
147             return (V) v;
148         }
149 
150         return initialize(threadLocalMap);
151     }
152 
153     private V initialize(InternalThreadLocalMap threadLocalMap) {
154         V v = null;
155         try {
156             v = initialValue();
157         } catch (Exception e) {
158             PlatformDependent.throwException(e);
159         }
160 
161         threadLocalMap.setIndexedVariable(index, v);
162         addToVariablesToRemove(threadLocalMap, this);
163         return v;
164     }
165 
166     /**
167      * Set the value for the current thread.
168      */
169     public final void set(V value) {
170         if (value != InternalThreadLocalMap.UNSET) {
171             set(InternalThreadLocalMap.get(), value);
172         } else {
173             remove();
174         }
175     }
176 
177     /**
178      * Set the value for the specified thread local map. The specified thread local map must be for the current thread.
179      */
180     public final void set(InternalThreadLocalMap threadLocalMap, V value) {
181         if (value != InternalThreadLocalMap.UNSET) {
182             if (threadLocalMap.setIndexedVariable(index, value)) {
183                 addToVariablesToRemove(threadLocalMap, this);
184             }
185         } else {
186             remove(threadLocalMap);
187         }
188     }
189 
190     /**
191      * Returns {@code true} if and only if this thread-local variable is set.
192      */
193     public final boolean isSet() {
194         return isSet(InternalThreadLocalMap.getIfSet());
195     }
196 
197     /**
198      * Returns {@code true} if and only if this thread-local variable is set.
199      * The specified thread local map must be for the current thread.
200      */
201     public final boolean isSet(InternalThreadLocalMap threadLocalMap) {
202         return threadLocalMap != null && threadLocalMap.isIndexedVariableSet(index);
203     }
204     /**
205      * Sets the value to uninitialized; a proceeding call to get() will trigger a call to initialValue().
206      */
207     public final void remove() {
208         remove(InternalThreadLocalMap.getIfSet());
209     }
210 
211     /**
212      * Sets the value to uninitialized for the specified thread local map;
213      * a proceeding call to get() will trigger a call to initialValue().
214      * The specified thread local map must be for the current thread.
215      */
216     @SuppressWarnings("unchecked")
217     public final void remove(InternalThreadLocalMap threadLocalMap) {
218         if (threadLocalMap == null) {
219             return;
220         }
221 
222         Object v = threadLocalMap.removeIndexedVariable(index);
223         removeFromVariablesToRemove(threadLocalMap, this);
224 
225         if (v != InternalThreadLocalMap.UNSET) {
226             try {
227                 onRemoval((V) v);
228             } catch (Exception e) {
229                 PlatformDependent.throwException(e);
230             }
231         }
232     }
233 
234     /**
235      * Returns the initial value for this thread-local variable.
236      */
237     protected V initialValue() throws Exception {
238         return null;
239     }
240 
241     /**
242      * Invoked when this thread local variable is removed by {@link #remove()}.
243      */
244     protected void onRemoval(@SuppressWarnings("UnusedParameters") V value) throws Exception { }
245 }