javamultithreadingvirtual-threadsjava-23

Thread::startVirtualThread as Threadfactory


Why does this code lead to a java.lang.IllegalThreadStateException?

newSingleThreadScheduledExecutor(Thread::startVirtualThread).scheduleWithFixedDelay(
   () -> System.out.println("Hello, World!"),
   0,
   1,
   TimeUnit.SECONDS
);

The JavaDoc for java.util.concurrent.ThreadFactory explicitly states:

An object that creates new threads on demand.

... and Thread::startVirtualThread is a Function<Runnable, Thread> (object) that should do this. Right?

I figure that the intended way is probably Thread.ofVirtual().factory() but I'm still clueless on why the other function doesn't work.


Solution

  • The JavaDoc for the ThreadFactory newThread method says:

    Constructs a new unstarted Thread to run the given runnable.

    The key is unstarted which means Thread.getState returns Thread.State.NEW.

    Thread.startVirtualThread creates a new virtual thread and immediately starts running it. So the thread state will not be NEW.

    The code in ThreadPoolExecutor checks the state of the thread returned by the factory and throws IllegalThreadStateException if it is not NEW.