I have the following code:
public void post(String message) {
final String mess = message;
(new Thread() {
public void run() {
while (true) {
try {
if (status.equals("serviceResolved")) {
output.println(mess);
Game.log.fine("The following message was successfully sent: " + mess);
break;
} else {
try {Thread.sleep(1000);} catch (InterruptedException ie) {}
}
} catch (NullPointerException e) {
try {Thread.sleep(1000);} catch (InterruptedException ie) {}
}
}
}
}).start();
}
In my log file I find a lot of lines like this:
The following message was successfully sent: blablabla
The following message was successfully sent: blablabla
The following message was successfully sent: blablabla
The following message was successfully sent: blablabla
And my program is not responding.
It seems to me that the break
command does not work. What can be a possible reason for that.
The interesting thing is that it happens not all the time. Sometimes my program works fine, sometimes the above described problem happens.
What is probably happening is the console is blocked waiting for a carriage return (i.e. for you to hit Enter) to then process your input. So your program is not running for every key press, but is waiting for an entire line to be entered. This is most apparent when you remove your do-while loop.
break statement is not working and the loop is running infinitely. The answer to your question is that the "break" statement refers to the for loop and not to the while loop.
If the while loop does not have a condition that allows it to break, this forms what is called an infinite loop. An infinite loop is a loop that goes on forever with no end. Normally in programs, infinite loops are not what the programmer desires. The programmer normally wants to create loops that have an end.
The keyword break works only on the current loop. You can't break the outmost loop from any enclosed loop with a single break , you'll need to set a flag in order to break at start of each loop when it becomes non-null.
Could it be that this line succeeds:
output.println(mess);
but this line is throwing a null pointer exception:
Game.log.fine(...
In this case you'll see the output on the console, but the break statement is never reached. Is Game.log
perhaps null?
What exactly does Game.log.fine do? Could it be that it throws a NullPtrException after output, or could it be that you call the post-method several times?
Remove the catch of the NullPointerException, this is bad style (occurrence of a NullPointerException is always a programming error) and add some more log-messages in the method (or use a debugger).
You are starting a new thread every time you call the post method. I thing the method is OK but caller program isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With