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

Alan Bateman Alan.Bateman at oracle.com
Tue Jan 25 08:15:37 UTC 2022


On 24/01/2022 20:47, Simon Herter wrote:
> 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?
I think you are asking about "custom schedulers" and whether the UI 
thread could be used as a carrier thread. This capability was exposed 
for some time but it needs more work to explore. So unlikely to be 
exposed in a first release. Experiments with using the AWT event 
dispatching thread (or the equivalent UI thread in other frameworks) as 
a carrier thread were inconclusive. Each virtual thread has its own 
identity and not clear if methods such as isEventDispatchThread would 
have change to test if the underlying carrier thread is the dispatching 
thread or not. A lot more work is required to answer some of the 
questions in this area.

-Alan




More information about the loom-dev mailing list