Thread-local variables Virtual threads support thread-local variables (ThreadLocal) and inheritable thread-local variables (InheritableThreadLocal), just like platform threads, so they can run existing code that uses thread locals. However, because virtual threads can be very numerous, use thread locals only after careful consideration. In particular, do not use thread locals to pool costly resources among multiple tasks sharing the same thread in a thread pool. Virtual threads should never be pooled since each is intended to run only a single task over its lifetime. We have removed many uses of thread locals from the JDK's java.base module in preparation for virtual threads in order to reduce memory footprint when running with millions of threads. The system property jdk.traceVirtualThreadLocals can be used to trigger a stack trace when a virtual thread sets the value of any thread-local variable. This diagnostic output may assist with removing thread locals when migrating code to us
评论