I have strange behavior of while(true) loop. Here is the code:
As a member of class I have:
static Queue<Object> response = new LinkedList<Object>();
… and a function:
private void read() {
while (true)
{
System.out.println("foo");
if(!(response.isEmpty()))
{
if((Boolean)response.peek() == true)
{
view.dispose();
LogInControler controler= new LogInControler();
disableMasterLogin();
response.poll();
return;
}
else if((Boolean)response.poll() == false)
{
JOptionPane.showMessageDialog(view.getRootPane(),
"Wrong username or password.");
view.tfUsername.requestFocus();
return;
}
}
}
}
When object is received from server(via Socket), InputController class pass that object to appropriate controller, in this case MasterLogInController and put it in Queue response.
I am waiting for that response in while(true) loop, but the problem is if I remove “System.out.printline(“foo”);” loop will be entered only once!? With this syso line I “force” while loop to do loops until response is received. What’s wrong here?
I assume you have several threads running.
System.out.printlncreates a memory barrier which probably helps your code see some variable which is otherwise not visible (because of lack of synchronization).In particular, your queue is not thread safe and does seem to be safely published. So it is very conceivable that:
whileloop might seeresponseas null ==> NullPointerExceptionreponse.isEmpty()might return false butresponse.peek()might return null, which you then cast to aBooleanand unbox in your conditionif((Boolean)xxx == true)==> NullPointerExceptionApart from the sound advice given in the comments to help understand the cause, you should make the code thread safe. For example, you could use a thread safe BlockingQueue. But that will probably not be enough (because of the way your various if / if / else if statements are laid out and the fact that the queue might be changed by another thread between each of those statements).