[英]Java is using 100% of CPU using sockets
我有一個在Linux機器上的tomcat上運行的Java應用程序。 該應用程序像套接字服務器一樣工作,大約連接了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");
}
}
}
我不知道發生了什么,正在准備很多東西,但無法解決問題。
似乎問題已解決。 EJP是正確的,如果消息不是70的倍數,則循環永遠不會結束。 我只需要更改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
}
}
非常感謝你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.