I have a problem which I don\'t really think has a solution but I\'ll try here anyway. My application uses a thread pool and some of the threads in this pool have an inherit
The constructor of a runnable runs in the thread of the caller, whereas the run method runs in the child thread. You can use this fact to transfer information from the parent to the child thread. See:
public class ThreadlocalApplication {
static public ThreadLocal tenantId = new ThreadLocal<>();
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
System.out.println(Thread.currentThread().getName());
ThreadlocalApplication.tenantId.set("4711");
executor.submit(new AsyncTask()).get();
executor.shutdown();
}
static class AsyncTask implements Runnable {
private String _tenantId;
public AsyncTask() {
System.out.println(Thread.currentThread().getName());
_tenantId = ThreadlocalApplication.tenantId.get();
}
@Override
public void run() {
ThreadlocalApplication.tenantId.set(_tenantId);
System.out.println(Thread.currentThread().getName());
System.out.println(ThreadlocalApplication.tenantId.get());
}
}
}
And this is the result
main
main
pool-1-thread-1
4711