我有一个 Java 应用程序在 Linux 机器中的 tomcat 上运行。这个应用程序像一个套接字服务器一样工作,其中连接了大约 15 个设备。似乎当设备发送一条大消息时,cpu 会增长到 100% 的使用率。问题是如果我取消部署应用程序,java 仍然拥有 99% 的 CPU。该应用程序有两个部分:
套接字服务器:
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();
}
与每个设备连接的每个套接字线程:
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");
}
}
}
我不明白发生了什么,我正在处理很多事情,但我无法解决问题。