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 private static final ThreadLocal<Context> localContext = new ThreadLocal<Context>(); 32 33 @Override doAttach(Context toAttach)34 public Context doAttach(Context toAttach) { 35 Context current = current(); 36 localContext.set(toAttach); 37 return current; 38 } 39 40 @Override detach(Context toDetach, Context toRestore)41 public void detach(Context toDetach, Context toRestore) { 42 if (current() != toDetach) { 43 // Log a severe message instead of throwing an exception as the context to attach is assumed 44 // to be the correct one and the unbalanced state represents a coding mistake in a lower 45 // layer in the stack that cannot be recovered from here. 46 log.log(Level.SEVERE, "Context was not attached when detaching", 47 new Throwable().fillInStackTrace()); 48 } 49 doAttach(toRestore); 50 } 51 52 @Override current()53 public Context current() { 54 return localContext.get(); 55 } 56 } 57