I need to continuously listen to a remote socket and react on given input.
public void listen(String ip, int port) {
try (
Socket socketListener = new Socket(ip, port);
BufferedReader portReader = new BufferedReader(new InputStreamReader(socketListener.getInputStream()));
) {
while (true) {
while (!portReader.ready()) {
// Wait for next PORT message
}
Logger.log(LogComponent.SOCKET, "Event received");
}
}
}
What am I doing so enormously wrong that the code above is using 100% CPU load?
While debugging I can see that the while-!portreader-loop is the evildoer. But most of the examples I've found are doing it the same way.
EDIT #1
Considering your comments I have following solution right now:
try {
Socket SocketListener = new Socket(ip, port);
BufferedReader portReader =
new BufferedReader(
new InputStreamReader(SocketListener.getInputStream())
);
// We do not use common while(true)-pattern for reading the input.
// Instead, we check for new input 3 times a second.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
executor.scheduleAtFixedRate(() -> {
try {
processInput(portReader);
} catch (IOException e) {
e.printStackTrace();
}
}, 0, 333, TimeUnit.MILLISECONDS);
} catch (Exception exception) {
exception.printStackTrace();
}
And processInput(0)
is doing the action now.
This ends in better performance results than using simply Thread.sleep() - though I don't understand why.
When using this approach: Can the code miss some messages from the socket? I mean during the intervals?