Problems trying to use Project Loom/Virtual Threads with OpenJDK 19-loom JAVA

Viewed 410

I'm trying to test the virtual threads reference loom project in Java and I'm using the following JDK 19-loom version:

enter image description here

  package com;

import java.util.concurrent.ThreadFactory;

    public class a {
    
    
        public static void main (String [] args) throws Exception{
            Runnable printThread = () -> System.out.println(Thread.currentThread());
    
            ThreadFactory virtualThreadFactory = Thread.builder().virtual().factory();
            ThreadFactory kernelThreadFactory = Thread.builder().factory();
    
            Thread virtualThread = virtualThreadFactory.newThread(printThread);
            Thread kernelThread = kernelThreadFactory.newThread(printThread);
    
            virtualThread.start();
            kernelThread.start();
    
        }
    }

And I have the following IntelliJ configuration:

enter image description here

But I am having the following error:

enter image description here

And it seems that the builder of the thread is not identified

enter image description here

I would like to know what else do I need?

1 Answers

You are using an outdated example.

With the current state of Loom, your example has to look like

public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory();
    ThreadFactory kernelThreadFactory = Thread.ofPlatform().factory();

    Thread virtualThread = virtualThreadFactory.newThread(printThread);
    Thread kernelThread = kernelThreadFactory.newThread(printThread);

    virtualThread.start();
    kernelThread.start();

    virtualThread.join();
    kernelThread.join();
}

but you can also use the simplified

public static void main(String[] args) throws InterruptedException {
    Runnable printThread = () -> System.out.println(Thread.currentThread());

    Thread virtualThread = Thread.startVirtualThread(printThread);
    Thread kernelThread = Thread.ofPlatform().start(printThread);

    virtualThread.join();
    kernelThread.join();
}

Keep in mind that this is work in progress and documents can become outdated quite fast.

Related