0

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 !!!

Ashish
  • 13
  • 4
  • No. Clicking the stop button in eclipse shuts down the whole jvm that executes your application. As far as I know there is no way of attaching some task to that stop button. – f1sh May 10 '16 at 13:36

1 Answers1

0
  1. 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();
    }
    
  2. 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

AnatolyG
  • 1,557
  • 8
  • 14