ThreadFactory for carrier threads, access to native thread, callback when carrier thread is mounted

Stephan B stephan.j.bircher at gmail.com
Sat Jan 7 18:31:22 UTC 2023


Hi loom dev team

The project I work on involves a great deal of native code where thread interaction between java and native code is vital. 
Therefore the java Thread was extended to hold a reference to the native thread data structure. Once a java thread is taken from the thread pool the runtime structure must only be attached to native thread which is done directly by updating the pointer in the native thread structure.

Like the following code illustrates

            var runtime = Runtime.current();
	    unsafe.putLong(thread + ThreadOffset.runtime, runtime.ptr);
            unsafe.putLong(thread + ThreadOffset.userContext, runner.getUserContext().getPtr());

Once the runtime state is attached any further JNI call to the native code can access the runtime data by calling (pthread_getspecific).

This could be achieved by having a custom ThreadFactory for the carrier thread pool used by virtual threads and by having a callback mechanism which informs once a Virtual Thread is mounted to the native thread.

Another problem which I see is that virtual threads hide the native java thread so native thread state can not be stored. 
ThreadLocal returns the local state of the virtual thread which is not of much use as one can simply store this state in the Task (Runnable).
There should be a way to access the native thread and to store state on that.
 
Thank you very much for considering these suggestions.  

- Stephan



More information about the loom-dev mailing list