So, my server app causing a huge cpu usage averaging about 95%. I think the reason is it keep spawning new thread but not closing it. how am I suppose to close a thread when any of this happen: refresh page, logout, browser closed.
My code is more or less like this for server part.
ThreadedEchoServer.java
public class ThreadedEchoServer {
// using port 2000
static final int PORT = 2000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new EchoThread(socket).start();
}
}
}
EchoThread.java
/*
Class for java server to accept incoming stream
and create a new thread to save log file data in server
*/
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
/*Create a File*/
int i = 1;
try {
File directory = new File("F:/temp/tmplog/" + getDate());
if(!directory.exists()) {
directory.mkdir();
}
String fileName = "F:/temp/tmplog/" + getDate() + "/" + getDateTime() + ".txt";
File file = new File(fileName);
//Double Make Sure it create the file
while(file.exists()) {
file = new File(fileName + "." + i);
i++;
}
FileOutputStream fis = new FileOutputStream(file, true);
PrintStream out = new PrintStream(fis);
System.setOut(out);
while (true) {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "US-ASCII"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException exception) {
// Just handle next request.
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignored) {
}
}
fis.close();
}
}
} catch (IOException ignored) {
}
}
This server app basicly will open a new and write a log file for every thread/client. I think the problem is I do not close the thread after use. that’s why it just keep spawning new thread.. Any help?
If I understood what you’re looking for, you can just use a timeout to handle this situation.
When the timeout expires, you’ll just terminate the thread.
EchoThread