1

I'm facing an unusual behavior when trying to experiment with java 19 virtual thread, the code below works perfectly with platform thread. but it exits suddenly when i switch to virtual thread. adding while(true); at the end solves the problem and the program keeps printing "hello". is it possible to use virtual thread with ScheduledExecutorService?

        ThreadFactory factory = Thread.ofVirtual().factory();
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(factory);
            scheduledExecutorService.scheduleAtFixedRate(() -> {
                System.out.println("hello");
            }, 0, 5000, TimeUnit.MILLISECONDS);
    }
   //while(true);
biiyamn
  • 476
  • 3
  • 9
  • 1
    From [the Javadoc](https://download.java.net/java/early_access/loom/docs/api/java.base/java/lang/Thread.html): "_Virtual threads are daemon threads and so do not prevent the Java virtual machine from terminating_". Seems similar to, but not exactly the same as, [this problem](https://stackoverflow.com/questions/51879659/completablefuture-is-not-getting-executed-if-i-use-the-executorservice-pool-it) (though you can't apply the same fix, as it looks like virtual threads are _always_ daemon threads, and you can't change that). – Slaw Jun 03 '22 at 16:30

1 Answers1

0

From the documentation:

Virtual threads are daemon threads and so do not prevent the Java virtual machine from terminating.

This appears to be absolute; there's no way to make a virtual thread non-daemon.

So, if you want to use a thread pool (scheduled or not) which uses virtual threads, then you'll need to make sure at least one non-daemon platform thread remains alive for as long as you need. Your while (true); loop currently does this, but in a way I strongly discourage; even sleeping the thread would be better, though still not great. In a more complex application, like a server or desktop application, you'll likely have one or more non-daemon threads doing work anyway (e.g., the "event loop" in a desktop application) that will keep the JVM alive.

Slaw
  • 37,820
  • 8
  • 53
  • 80