Unable to play - is Java determinate multi-threading possible?

Is it possible to run a multi-threaded Java application in a deterministic way? I mean, always have the same thread switching in two different launches of my application.

The reason for this is to run the simulation under exactly the same conditions in each run.

A similar case is the case when using a random number generator you can get an arbitrary seed to always get the same "random" sequence.

+6
source share
3 answers

I do not know what a practical way to do this.

In theory, a bytecode interpreter could be implemented with completely deterministic behavior under certain assumptions 1 . You will need to simulate multiple threads, implementing threads and thread scheduling entirely in software and using one proprietary thread.


1 - For example, there is no I / O and the system clock is not used.

+4
source

No, it is impossible (except to simulate it yourself) to use multiple threads that alternate the same every time. Threads are not designed for this.

If you want deterministic results, do not use streams.

+4
source

As indicated by OldCurmudgeon , this is not possible with multithreading.

If you decide to use a single Thread , I prefer newSingleThreadExecutor to regular Thread because of the flexibility and advantages of newSingleThreadExecutor

Use

newSingleThreadExecutor from Executors

 public static ExecutorService newSingleThreadExecutor() 

Creates an Executor that uses a single workflow working with an unlimited queue. (Note that if this single thread terminates due to a run-time failure before shutting down, a new one will take its place if necessary to do the following tasks.)

The execution of tasks is guaranteed sequentially, and no more than one task will act at any time. Unlike the equivalent newFixedThreadPool (1), the returned executor is guaranteed not to be reconfigured to use additional threads.

Related SE questions:

Difference between Executors.newFixedThreadPool (1) and Executors.newSingleThreadExecutor ()

ExecutorService vs Casual Thread Spawner

0
source

All Articles