Under what circumstances will virtual threads expand the number of underlying carrier threads?

225 views Asked by At

In the jep444, I see "The implementations of these blocking operations compensate for the capture of the OS thread by temporarily expanding the parallelism of the scheduler". Under what circumstances will virtual threads expand the number of underlying carrier threads?

Can you give me some code to reach this?

1

There are 1 answers

0
FlyChenKai On
public class CarrierThreadExpandTest {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
        File file = new File("/Users/info.log");
        for (int i = 0; i < 32; i++) {
            executorService.execute(() -> {
                while (true) {
                    try (FileInputStream fis = new FileInputStream(file)) {
                        int content;
                        while ((content = fis.read()) != -1) {
                            System.out.print((char) content);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                }
            });
        }
        Thread.sleep(1000 * 60 * 60);
    }
}

$ jps
$ jstack pid

look at the "ForkJoinPool-1-worker-xx" thread.