3 ms·
Is it possible to override the scheduler from user code? i.e. if you wanted to control scheduling yourself for some reason.
by ryanworl 6y ago
Is it possible to override the scheduler from user code? i.e. if you wanted to control scheduling yourself for some reason.
- pron 6y agoYes, and even on a per-thread basis.
- ryanworl 6y agoThanks! Is there an example "Hello World" executor that demonstrates the minimum functionality needed? I would like an executor that runs all tasks on a single thread and schedules them deterministically for testing.
- pron 6y agovar 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();