Hello, im running an app that has a class that implements
ServletContextListener (Server class), on that class i create a thread of
Listener (that implements Runnable)
Listener starts a ServerSocket that listen on a port, and in a periodically
manner, this app receives a string, parses the string and stores the data
inside a database. Flow is
1. receive a tcp connection (syn , syn+ack, ack)
2. receives lines over and over again inside this connections (each line is
parsed and stored)
Below is the code of Listener class and how i call this class from Server
class. What im facing is im not able to stop Listener in a correct way. doing
Listener.interrupt() does nothing. How can i safely stop Listener thread
Thanks in advance
--
//initalize listener
Listener = new Thread((Runnable) new
Listener(Integer.parseInt(prop.getProperty("listenonport"))));
if (!Listener.isAlive()) {
Listener.setName("ListenerThread");
Listener.setDaemon(true);
Listener.start();
}
--
package lesi.p1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;
/**
*
* @author alz
*/
public class Listener implements Runnable {
private static org.apache.log4j.Logger log =
Logger.getLogger(Listener.class);
private Socket clientSocket = null;
private ServerSocket serverSocket = null;
private int listenport = 0;
Thread CDRThread = null;
public Listener(int port) {
this.listenport = port;
}
@Override
public void run() {
try {
log.debug("About to listen on port: " + this.listenport);
serverSocket = new ServerSocket(this.listenport);
while (true) {
clientSocket = serverSocket.accept();
CDRThread = new Thread((Runnable) new CDRExec(clientSocket));
if (!CDRThread.isAlive()) {
CDRThread.setName("CDRThread");
CDRThread.setDaemon(true);
CDRThread.start();
}
}
} catch (IOException e) {
log.error("Catcher IOException: ", e);
} finally {
try {
log.info("Closing socket");
serverSocket.close();
} catch (IOException ex) {
log.error("Error trying to close port", ex);
}
if (CDRThread.isAlive()) {
log.info("Stopping CDRExec Thread");
CDRThread.interrupt();
}
}
}
class CDRExec implements Runnable {
private Socket client = null;
public CDRExec(Socket client) {
this.client = client;
}
@Override
public void run() {
String inputLine = "";
StringBuilder sb = new StringBuilder();
Parser p = null;
BufferedReader in = null;
log.debug("Thread: " + Thread.currentThread().getId() + " name: " +
Thread.currentThread().getName());
try {
p = new Parser();
in = new BufferedReader(new
InputStreamReader(client.getInputStream()));
while (true) {
if ((inputLine = in.readLine()) != null) {
p.parseCDR(inputLine);
}
inputLine = null;
}
} catch (IOException e1) {
try {
in.close();
} catch (Throwable ignore) {
}
p = null;
}
}
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]