Skip to content

Instantly share code, notes, and snippets.

@hengyunabc
Created February 6, 2018 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hengyunabc/8fba507d578decd098391f9b08f6a0f2 to your computer and use it in GitHub Desktop.
Save hengyunabc/8fba507d578decd098391f9b08f6a0f2 to your computer and use it in GitHub Desktop.
一个ThreadLocal 在不同ClassLoader下失效的问题
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
import java.lang.reflect.Method;
import java.net.URLClassLoader;
public class ThreadLocalTest {
static private URLClassLoader userClassLoader;
static {
URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
userClassLoader = new URLClassLoader(systemClassLoader.getURLs(), systemClassLoader.getParent());
}
public static void main(String[] args) throws Exception {
System.err.println(ThreadId.get());
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.err.println(ThreadId.get());
}
});
t1.start();
t1.join();
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Class<?> clazz = loadClassFromUserClassLoader(ThreadId.class.getName());
Method getMethod = clazz.getMethod("get");
System.err.println(getMethod.invoke(null));
} catch (Exception e) {
e.printStackTrace();
}
}
});
t2.start();
}
public static Class<?> loadClassFromUserClassLoader(String name) throws ClassNotFoundException {
return userClassLoader.loadClass(name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment