ExecutorService that uses current thread as (the only) carrier thread?

Simon Herter sim.herter at gmail.com
Mon Jan 24 20:47:57 UTC 2022


Hi,

I was wondering if it will be possible to have an ExecutorService that
spawns a new virtual thread for every task, but yields on 'close' and
uses the current thread as (the only) carrier thread.


Consider the following example:


    ReentrantLock lock = new ReentrantLock();
    lock.lock();
    try (var e = Executors.newVirtualThreadPerTaskWithCurrentThreadAsCarrierExecutor()) {
        e.submit(
            () -> {
              lock.lock();
              try {
                System.out.println("Hello from " + Thread.currentThread().getName());
              } finally {
                lock.unlock();
              }
            });
    }



If the current thread is the only carrier thread, this shouldn't deadlock.

Thinking of (badly designed) GUI applications that trigger independent
blocking I/O operations in a loop in the UI thread, I can imagine that
this could provide some nice performance improvements without changing
the design. At least the 'waiting for I/O' can happen in parallel.

Will something like this be part of the JDK? Will we have to implement
it ourselves? Or is this a stupid idea that cannot work at all?

Thanks,
Simon


More information about the loom-dev mailing list