Search code examples
javamultithreadingjava-threads

How to check if Java thread is idle or calculating?


I'm running some tick/timestep based simulations. After every tick objects move and states change. I'm trying to compare 3 different strategies for the same goal, the fastest strategy wins. The code looks as follows

for(Strategy strategy : strategies){
    StopWatch watch.start();
    while(termination_condition){
        // goal is different for every strategy
        goal = getGoal(strategy);
        doStuff();
        moveObjects();
        changeStates();
        sleep(sleepAmount);
    }
    watch.stop();
}

public Goal getGoal(Strategy strategy){
    switch(strategy):{
    case 1:
    case 2:
    case 3:
    }
    return goal;
}

Now some strategies are really simple and require nearly no calculations. One is just give me a random goal. Others involve elaborate planning. Now I would like to have sleepAmount as low as possible, because I need to run many simulations. But I'm afraid that if I put it too low the easier strategies might be faster, because they require less calculations. Now my question is, is there a way to check if a thread is calculating or actually really sleeping/idle? Or how can I find the lowest possible limit of sleepAmount so that every timestep takes exactly the sleep amount of time and not longer? So that the difference between the strategies is only that some take more timesteps but not that some have timesteps that are longer.

My current sleepAmount is 50ms and everything seems to be running fine, but one trial takes about 1 minute and I want to do around 50 trials for around 5 strategies. This takes several hours which is way too long. So any ideas?

EDIT: I measure time as elapsed time time = (System.currentTimeMillis() - startTime);


Solution

  • I think you want a CyclicBarrier object. When each strategy finishes one step (cycle) it waits at the barrier. When all threads are waiting, one thread will be given permission to perform some clean up activity to prepare for the next cycle. Then all threads are released to perform the step. There is an example in the javadocs.