context: Avoid leaking ClassLoader through ThreadLocal

This commit is contained in:
Eric Anderson 2019-01-25 21:57:26 -08:00
parent 27253353e7
commit 55b08e67d4
2 changed files with 53 additions and 1 deletions

View File

@ -46,7 +46,19 @@ final class ThreadLocalContextStorage extends Context.Storage {
log.log(Level.SEVERE, "Context was not attached when detaching", log.log(Level.SEVERE, "Context was not attached when detaching",
new Throwable().fillInStackTrace()); new Throwable().fillInStackTrace());
} }
doAttach(toRestore); if (toRestore != Context.ROOT) {
localContext.set(toRestore);
} else {
// Avoid leaking our ClassLoader via ROOT if this Thread is reused across multiple
// ClassLoaders, as is common for Servlet Containers. The ThreadLocal is weakly referenced by
// the Thread, but its current value is strongly referenced and only lazily collected as new
// ThreadLocals are created.
//
// Use set(null) instead of remove() since remove() deletes the entry which is then re-created
// on the next get() (because of initialValue() handling). set(null) has same performance as
// set(toRestore).
localContext.set(null);
}
} }
@Override @Override

View File

@ -0,0 +1,40 @@
/*
* Copyright 2019 The gRPC Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.grpc;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class ThreadLocalContextStorageTest {
private static final Context.Key<Object> KEY = Context.key("test-key");
private ThreadLocalContextStorage storage = new ThreadLocalContextStorage();
@Test
public void detach_threadLocalClearedOnRoot() {
Context context = Context.ROOT.withValue(KEY, new Object());
Context old = storage.doAttach(context);
assertThat(old).isNull();
assertThat(storage.current()).isSameAs(context);
// Users see nulls converted to ROOT, so they will pass non-null as the "old" value
storage.detach(context, Context.ROOT);
assertThat(storage.current()).isNull();
}
}