• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016 The gRPC 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 io.grpc;
18 
19 import java.util.logging.Level;
20 import java.util.logging.Logger;
21 
22 /**
23  * A {@link ThreadLocal}-based context storage implementation.  Used by default.
24  */
25 final class ThreadLocalContextStorage extends Context.Storage {
26   private static final Logger log = Logger.getLogger(ThreadLocalContextStorage.class.getName());
27 
28   /**
29    * Currently bound context.
30    */
31   // VisibleForTesting
32   static final ThreadLocal<Context> localContext = new ThreadLocal<>();
33 
34   @Override
doAttach(Context toAttach)35   public Context doAttach(Context toAttach) {
36     Context current = current();
37     localContext.set(toAttach);
38     return current;
39   }
40 
41   @Override
detach(Context toDetach, Context toRestore)42   public void detach(Context toDetach, Context toRestore) {
43     if (current() != toDetach) {
44       // Log a severe message instead of throwing an exception as the context to attach is assumed
45       // to be the correct one and the unbalanced state represents a coding mistake in a lower
46       // layer in the stack that cannot be recovered from here.
47       log.log(Level.SEVERE, "Context was not attached when detaching",
48           new Throwable().fillInStackTrace());
49     }
50     if (toRestore != Context.ROOT) {
51       localContext.set(toRestore);
52     } else {
53       // Avoid leaking our ClassLoader via ROOT if this Thread is reused across multiple
54       // ClassLoaders, as is common for Servlet Containers. The ThreadLocal is weakly referenced by
55       // the Thread, but its current value is strongly referenced and only lazily collected as new
56       // ThreadLocals are created.
57       //
58       // Use set(null) instead of remove() since remove() deletes the entry which is then re-created
59       // on the next get() (because of initialValue() handling). set(null) has same performance as
60       // set(toRestore).
61       localContext.set(null);
62     }
63   }
64 
65   @Override
current()66   public Context current() {
67     Context current = localContext.get();
68     if (current == null) {
69       return Context.ROOT;
70     }
71     return current;
72   }
73 }
74