thunkware / virtual-threads-bridge

Use Java21's Virtual Threads API in Java 8+
MIT License
8 stars 3 forks source link

ExecutorTool creates a newVirtualThreadPerTaskExecutor() where thread names are empty #20

Closed dhoard closed 3 months ago

dhoard commented 4 months ago

Summary

Logging code executed in a virtual thread doesn't have a thread name to log. This is required for log print/thread correlation.

Expected Behavior

Thread.currentThread().getName()

.. should return a name

Actual Behavior

Thread.currentThread().getName()

... returns an empty ("") String

Test

    @Test
    void testNewVirtualThreadPerTaskExecutor() throws Throwable {
        assertThat(ExecutorTool.hasVirtualThreads()).isTrue();

        AtomicReference<Throwable> throwable = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        ExecutorService executor = ExecutorTool.newVirtualThreadPerTaskExecutor();
        executor.submit(() -> {
            assertThat(ThreadTool.isVirtual()).isTrue();
            try {
                assertThat(Thread.currentThread().getName()).isNotNull();
                assertThat(Thread.currentThread().getName()).isNotEmpty();
            } catch (Throwable t) {
                throwable.set(t);
            }
            latch.countDown();
        });
        assertThatNoException().isThrownBy(() -> latch.await(1, TimeUnit.SECONDS));
        assertThat(latch.getCount()).isZero();

        if (throwable.get() != null) {
            throw throwable.get();
        }
    }

Possible Solution

Implement a new interface ThreadNameProvider to allow code to set the thread name.

public interface ThreadNameProvider {

    String getThreadName();
}

Add a new method to ExecutorTool that accepts a ThreadNameProvider

    public static ExecutorService newVirtualThreadPerTaskExecutor(ThreadNameProvider threadNameProvider) {
        return getThreadProvider().newVirtualThreadPerTaskExecutor(threadNameProvider);
    }
maxxedev commented 3 months ago

Please see if pull request https://github.com/thunkware/virtual-threads-bridge/pull/23 provides what you want. Thanks

dhoard commented 3 months ago

That should work. Thanks!