Abstract: In this newsletter we puzzle about what happens when we print output from a virtual thread, then play around with class loaders and hidden classes. Be ready to stub your toe on some rusty metal sticking out of the sand.
Welcome to the 339th edition of The Java(tm) Specialists' Newsletter, sent to you from the beautiful, but wild, Island of Crete. Today is our 26th newsletter anniversary, and what a road it has been! I've met amazing people all over the world, made friends everywhere, was (apparently) the first name to be put forward to be a Java Champion, received the super exclusive Java Community Lifetime Achievement, and have created the best advanced Java training in the world, inspired by the weird and wonderful discoveries in this newsletter. For the last 4 years, ChatGPT has also joined as an avid fan, and lovingly sends human readers my way.
Last night, Greece sent us an urgent emergency warning: "Civil Protection. Due to severe weather conditions and gale-force winds in the Regional Units of Chania and Rethymno, limit your movements from today and throughout Monday." And of course that didn't stop me from running on the beach this morning, dodging rocks and surging surf. On this big desolate beach, I somehow managed to catch my toe on a piece of sun umbrella. This is how I am with Java bugs. I go coding where only fools would venture. And then I stumble over weird bugs sticking out from the sand. More later.
We are running our Black Friday and Cyberpunk Monday specials, all the way until December the 4th. Yes, we are all "coding" with genAI now, and that means we need to be even sharper than before. ChatGPT guesses with amazing accuracy what my writing is, but it cannot write like me. Same goes for teaching. The real secret is not what you include in the training, but what you exclude.
javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge.
Here is a fun Java puzzler that I hope all of us would get right by now. What is the most likely output when we run this class?
public class JavaPuzzler1 {
private static class WelcomeScript {
static {
Thread.startVirtualThread(() ->
System.out.println("Hello world"));
}
}
public static void main(String... args) {
new WelcomeScript();
}
}
You guessed it - most likely we would see nothing at all! Virtual threads run on carrier threads from a ForkJoinPool. These are always daemon threads. In our small class, the only non-daemon thread is "main" and when that terminates, all daemon threads are also abruptly terminated.
Let's add a join() to make sure that we see the output.
What's do we see now? Think about it, then run the code to verify:
public class JavaPuzzler2 {
private static class WelcomeScript {
static {
var hello = Thread.startVirtualThread(() ->
System.out.println("Hello world"));
try {
hello.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String... args) {
new WelcomeScript();
}
}
Did you try it out? I hope you did before reading further...
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Output is: Still nothing! Except this time, the program also does not terminate.
Here is a partial thread dump in Java 25.0.4.1 LTS:
"main" #3 [6147] waiting on condition ...
java.lang.Thread.State: WAITING (parking)
* snip *
at java.lang.Thread.join(java.base@25.0.4.1/Thread.java:1963)
at JavaPuzzler2$WelcomeScript.<clinit>(JavaPuzzler2.java:7)
at JavaPuzzler2.main(JavaPuzzler2.java:15)
"ForkJoinPool-1-worker-1" #27 [42755] daemon
Carrying virtual thread #26
at jdk.internal.vm.Continuation.run
* snip *
Mounted virtual thread #26
at JavaPuzzler2$WelcomeScript$$Lambda/0x0000200001154420.run(Unknown Source)
- waiting on the Class initialization monitor for JavaPuzzler2$WelcomeScript
at java.lang.Thread.runWith(java.base@25.0.4.1/Thread.java:1487)
Aha, we immediately see what is going on. It is the classic class
initialization deadlock. A thread is blocked from accessing any static
elements of a class until <clinit> - the class initializer
block - has completed. We can see this from the message waiting on
the Class initialization monitor for JavaPuzzler2$WelcomeScript.
You might wonder what static resource the thread
is accessing? The lambda is in this case implemented as a static method,
which we can see with javap -c -private
JavaPuzzler2\$WelcomeScript.class:
private static void lambda$static$0();
Code:
0: getstatic #7 // Field System.out
3: ldc #13 // String Hello world
5: invokevirtual #15 // Method PrintStream.println
8: return
This was "enhanced" in Java 26 with JDK-8369238, where they no longer keep the virtual thread mounted in a class initialization deadlock. The virtual thread would still appear in the full thread dump, but with no clue as to why it is stuck.
Now it gets interesting. Note that we now have one carrier thread
permanently blocked with that class initialization deadlock in Java 25.
We could jam up all the carrier threads, by converting our
WelcomeScript class into a byte[]
and then loading it into one new ClassLoader per carrier thread.
(See newsletter 338 for how to
know what the carrier parallelism is).
Here is how we could completely jam up the carrier thread pool in
Java 25, so that we would never see the output from main()
"This is so cool!!!":
import jdk.management.VirtualThreadSchedulerMXBean;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.lang.management.ManagementFactory;
public class CarrierThreadMuncher {
private static class WelcomeScript {
static {
var hello = Thread.startVirtualThread(() ->
System.out.println("Hello world"));
try {
hello.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String... args)
throws Exception {
new CarrierThreadMuncher().run();
}
public final void run() throws Exception {
createOneClassPerCarrierThread();
Thread.sleep(1000);
var cool = Thread.startVirtualThread(() ->
System.out.println("This is so cool!!!"));
cool.join();
}
private void createOneClassPerCarrierThread()
throws IOException {
var bytes = getWelcomeScriptClassBytes();
var carrierParallelism = getCarrierParallelism();
for (var i = 0; i < carrierParallelism; i++) {
Thread.ofPlatform()
.daemon()
.name("initializer-" + i)
.start(() -> createJammedClass(bytes));
}
}
private static byte[] getWelcomeScriptClassBytes()
throws IOException {
var filename = WelcomeScript.class.getName()
.replace('.', '/') + ".class";
try (var in = WelcomeScript.class
.getResourceAsStream("/" + filename)) {
return in.readAllBytes();
}
}
// https://www.javaspecialists.eu/archive/Issue338.html
private static int getCarrierParallelism() {
return ManagementFactory.getPlatformMXBean(
VirtualThreadSchedulerMXBean.class)
.getParallelism();
}
protected void createJammedClass(byte[] bytes) {
try {
var loader = new ClassLoader() {
public Class<?> define(byte[] bytes) {
return defineClass(null, bytes,
0, bytes.length);
}
};
var clazz = loader.define(bytes);
Class.forName(
clazz.getName(), true, loader);
} catch (ClassNotFoundException e) {
throw new AssertionError(e);
}
}
}
Fortunately, since Java 26, virtual threads get unmounted cleanly and so the output appears. I doubt this is ever a real-world problem. Back porting the fix to Java 25 seems like a huge amount of work, so will probably never be done. My policy is to always be on the latest release of the Oracle OpenJDK on my JavaSpecialists server. I also recommend for companies to set up their CI/CD pipeline to make it feasible to upgrade quickly and easily.
But let's not stop here. Whilst playing around with this, I stubbed my
toe on another rusty umbrella pole, that of hidden classes. Since Java
15, we can create "hidden classes". These are used internally to create
helper classes, such as lambda implementation classes. What is
interesting is that these classes do not need to have a distinct name,
thus we can use the same byte[] for many
distinct hidden classes, all living in the same ClassLoader. Here is how
we could use them:
import java.lang.invoke.MethodHandles;
public class CarrierThreadMuncherHidden extends
CarrierThreadMuncher {
public static void main(String... args)
throws Exception {
new CarrierThreadMuncherHidden().run();
}
@Override
protected void createJammedClass(byte[] bytes) {
var lookup = MethodHandles.lookup();
try {
var hidden = lookup.defineHiddenClass(
bytes, false);
hidden.ensureInitialized(
hidden.lookupClass());
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
}
However, when we cause the class initialization deadlock with hidden classes, the virtual threads are not unmounted, not even in the latest versions of Java. I've logged a bug, but I don't think this is high priority, so not sure if/when it will be fixed.
Kind regards
Heinz
We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.