2

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?

  • 2
    Have you tried compiling this outside of IntelliJ? If IntelliJ uses the --release flag with language level 11 you will only get library symbols from 11. AFAIK 19 doesn't work with IntelliJ currently though (maybe the EA version supports it...). – Jorn Vernee Jan 31 '22 at 22:31

1 Answers1

6

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.

Holger
  • 285,553
  • 42
  • 434
  • 765