Reputation: 71
I have a Java application running on a tomcat that is in a Linux machine. This application works like a socket server, where about 15 devices are connected. Its seems like when a device sends a big message the cpu grows up until 100% usage. Te problem is that if I undeploy the application, java is still having 99% of the CPU. The application has two parts:
Socket server:
public void iniciarSocket() {
Runnable serverTask = new Runnable() {
@Override
public void run() {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Waiting a connection");
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
System.out.println("Client connected");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
new SocketThread(socket).start();
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
}
Each socket thread, which connect with each device:
public void run() {
try {
//Output channel
DataOutputStream salida;
salida = new DataOutputStream(socket.getOutputStream());
System.out.println("Client connected.... ");
byte[] buff = new byte[1024];
int bytesLeidos = 0;
socket.setSoTimeout(300000);
System.out.println("Timeout: " + socket.getSoTimeout());
while((bytesLeidos = socket.getInputStream().read(buff, 0, buff.length)) > -1) {
System.out.println("Bytes leidos: " + bytesLeidos);
if ((bytesLeidos == 70) && (Protocolo.isStatusMessage(buff))) {
Protocolo.decode(buff, salida);
} else {
int offset = 0;
while (offset < bytesLeidos) {
while ((offset + 70 <= bytesLeidos) &&(!Protocolo.isStatusMessageWithOffset(buff, offset))) {
offset++;
}
if ((offset + 70 <= bytesLeidos) &&(Protocolo.isStatusMessageWithOffset(buff, offset))) {
Protocolo.decodeWithOffset(buff, offset, salida);
offset += 70;
}
}
}
}
} catch (Exception e) {
System.out.println();
} finally {
System.out.println("Communication ended");
try {
socket.close();
} catch (Exception e) {
System.out.println("Socket not closed");
}
}
}
I don't understand what is happening and I'm traying a lot of things but I can't to solve the problem.
Upvotes: 1
Views: 2417
Reputation: 71
Seems that the problem is solved. EJP was right, if message is not multiple of 70 the loop never ends. I only had to change socketThread.
while((bytesLeidos = socket.getInputStream().read(buff, 0, buff.length)) > -1) {
System.out.println("Bytes leidos: " + bytesLeidos);
if ((bytesLeidos == 70) && (Protocolo.isStatusMessage(buff))) {
Protocolo.decode(buff, salida);
} else {
int offset = 0;
// Code changed
while (offset < bytesLeidos) {
if (Protocolo.isStatusMessageWithOffset(buff, offset)) {
// decodificar
Protocolo.decodeWithOffset(buff, offset, salida);
offset += 70;
} else {
offset++;
}
}
// End code changed
}
}
Thank you very much.
Upvotes: 1