Closed dhoard closed 3 months ago
Logging code executed in a virtual thread doesn't have a thread name to log. This is required for log print/thread correlation.
Thread.currentThread().getName()
.. should return a name
... returns an empty ("") String
@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(); } }
Implement a new interface ThreadNameProvider to allow code to set the thread name.
ThreadNameProvider
public interface ThreadNameProvider { String getThreadName(); }
Add a new method to ExecutorTool that accepts a ThreadNameProvider
ExecutorTool
public static ExecutorService newVirtualThreadPerTaskExecutor(ThreadNameProvider threadNameProvider) { return getThreadProvider().newVirtualThreadPerTaskExecutor(threadNameProvider); }
Please see if pull request https://github.com/thunkware/virtual-threads-bridge/pull/23 provides what you want. Thanks
That should work. Thanks!
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
.. should return a name
Actual Behavior
... returns an empty ("") String
Test
Possible Solution
Implement a new interface
ThreadNameProvider
to allow code to set the thread name.Add a new method to
ExecutorTool
that accepts aThreadNameProvider