I have an endless thread running in my code. This thread creates UDP read methods and listens on the connection endlessly.
What I want to do is to execute a piece of code once I stop the thread execution manually (by clicking the stop button in eclipse).
Is their a possible way of achieving this ?
While searching the same I came across a onDestroy() method but sadly that is applicable for Android Java only !!!
First of all, the right way to stop a network reading thread is to close the socket. Then read/receive method throws an exception and you catch it
private final DatagramSocket udpSocket;
private volatile boolean closed; // or AtomicBoolean
...
public synchronized void start() throws IOException {
if (closed) {
throw new IOException("Closed");
}
new Thread(new Runnable() {
@Override
public void run() {
final byte[] buffer = new byte[1024];
final DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
Throwable error = null;
try {
while(true) {
udpSocket.receive(dp);
final String message = new String(buffer, 0, dp.getLength());
System.out.println(message);
}
} catch (Throwable t) {
if (!closed) {
error = t;
}
}
if (error != null) {
// do some work for error
}
}
}).start();
}
public void close() throws IOException {
synchronized(this) {
if (closed) return;
closed = true;
}
udpSocket.close();
}
When you click STOP button in an IDE, usually you terminate (abnormally)/kill immediately your JVM process. I'd suggest to run your process in console and use Ctrl+C to stop the process and add a ShutdownHook:
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(
new Thread(
new Runnable() {
@Override
public void run() {
System.out.println("Shutdown");
}
}));
}
or run it in Eclipse but stop with taskkill on Windows/kill on Linux from command line interface to close JVM process normally.
See details at http://www.oracle.com/technetwork/java/javase/signals-139944.html https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29