Java / Java 21 Virtual Threads Interview questions
How do you check if a thread is virtual?
Java 21 added an instance method, isVirtual(), directly on Thread, so you can check any thread reference at runtime.
Thread current = Thread.currentThread(); if (current.isVirtual()) { System.out.println("Running on a virtual thread"); } else { System.out.println("Running on a platform thread"); }
This is useful in logging, diagnostics, or libraries that need to behave differently depending on which kind of thread is calling them, for instance to avoid pooling logic that only makes sense for platform threads.
More Related questions...