mercredi 29 juin 2016

Stuck at an infinite loop unless printing result

I am trying to test a use case where I need to launch two threads, but the second one needs to wait for a particular state to happen.

The first thread launches the resolution process of a tournament in order to calculate its schedules. The second thread stops the resolution process.

@Test
public void stopResolutionProcessTest() throws InterruptedException {
    TournamentSolver solver = tournament.getSolver();

    Thread solveThread = new Thread(tournament::solve);
    solveThread.start();

    while (solver.getResolutionState() != TournamentSolver.ResolutionState.COMPUTING);

    Thread stopThread = new Thread(solver::stopResolutionProcess);
    stopThread.start();

    solveThread.join();
    stopThread.join();

    assertEquals(TournamentSolver.ResolutionState.INCOMPLETE, solver.getResolutionState());
}

The main thread gets stuck in the while loop, as if it were infinite.

However, if I just print the resolution state inside the loop, the test runs as expected:

while (solver.getResolutionState() != TournamentSolver.ResolutionState.COMPUTING)
    System.out.println(solver.getResolutionState());

I have no explanation for this; I feel like I am back several years in the past when I was studying concurrency and unexpected things I couldn't explain happened.

Could anybody shed some light on what's going on?

Edit: alright I set my getResolutionState() as synchronized but I still don't understand why this helps or why printing the state would render the described results.

Aucun commentaire:

Enregistrer un commentaire