Search code examples
javatermination

Weird Java problem, while loop termination


I have a piece of code that looks like this:

Algorithm a = null;  
while(a == null)  
{  
    a = grid.getAlgorithm();  
}  

getAlgorithm() in my Grid class returns some subtype of Algorithm depending on what the user chooses from some options.

My problem is that even after an algorithm is selected, the loop never terminates. However, that's not the tricky bit, if I simply place a System.out.println("Got here"); after my call to getAlgorithm(), the program runs perfectly fine and the loop terminates as intended.

My question is: why does adding that magic print statement suddenly make the loop terminate?

Moreover, this issue first came up when I started using my new laptop, I doubt that's related, but I figured it would be worth mentioning.

Edit: The program in question is NOT multithreaded. The code for getAlgorithm() is:

public Algorithm getAlgorithm ()  
{  
    return algorithm;  
}

Where algorithm is initially null, but will change value upon some user input.


Solution

  • You are doing active polling. This is a bad practice. You should at least let the polling thread sleep (with Thread.sleep). Since println does some io, it probably does just that. If your app is not multithreaded it is unlikely to work at all.