3 ms·
var myThreadFactory = Thread.builder().virtual(Executors.newSingleThreadExecutor()).factory(); All threads created by this thread factory will be scheduled to
by pron 6y ago
var myThreadFactory = Thread.builder().virtual(Executors.newSingleThreadExecutor()).factory();
All threads created by this thread factory will be scheduled to the same kernel thread.
- Cojen 6y agoDoes this example fully answer the question? Does this allow the tasks to be scheduled deterministically? If I'm very careful and write the tasks such that they make blocking calls at specific locations, then yes. Otherwise, is there any feedback to inform me that tasks are switching context at places I didn't expect? Is it possible to define a custom scheduler that can simply print debug messages at every context switch?
- pron 6y agoIt answers the question with a "hello, world." To do more sophisticated stuff, like what you want, you'll need to replace or wrap the standard single-thread Executor with your own Executor. There is exactly one method you need to implement. For example: Executor ste = Executors.newSingleThreadExecutor(); Executor myExecutor = task -> { if (task instanceof Thread.VirtualThreadTask vtt) System.out.println("Scheduling " + vtt.thread() + " on " + Thread.currentThread()); ste.execute(task); if (task instanceof Thread.VirtualThreadTask vtt) System.out.println("Descheduled " + vtt.thread() + " from " + Thread.currentThread()); } var myThreadFactory = Thread.builder().virtual(myExecutor).factory();