Is this possible to run multithreaded Java application in a deterministic fashion? I mean to have always the same thread switching in two different runs of my application.
No it is not possible (other than to simulate it yourself) to use multiple threads interleaving in the same way each time around. Threads are not designed to do that.
If you want deterministic results, don't use threads.
As quoted by OldCurmudgeon
, it's not possible with multi threading.
If you decide to use single Thread
, I prefer newSingleThreadExecutor
to normal Thread
due to flexibility and advantages of newSingleThreadExecutor
Use
newSingleThreadExecutor from Executors
public static ExecutorService newSingleThreadExecutor()
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)
Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Related SE questions:
Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()
ExecutorService vs Casual Thread Spawner
I am not aware of any practical way to do this.
In theory, it would be possible to implement a bytecode interpreter with an entirely deterministic behavior under certain assumptions1. You would need to simulate the multiple threads by implementing the threads and the thread scheduling entirely in software and using a single native thread.
1 - For example, no I/O, and no use of the system clock.