Some sophisticated methods can be used here. A watchdog file is one option. RMI may be different. But in fact, the mechanisms required here are quite simple, so I would like to propose another (very simple) solution.
Note. This solution is just one option showing that this can be done like this. This is not a general recommendation, and whether it is “good” or not depends on the application.
The solution is simply based on Sockets. The ServerSocket#accept method already encapsulates the necessary functions:
Listens to the connection to this socket and accepts it. The method blocks until a connection is made.
Based on this, it is trivial to create such a "remote control": the server just waits for a connection and sets a flag when opening a connection:
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.atomic.AtomicBoolean; class RemoteExitServer { private final AtomicBoolean flag = new AtomicBoolean(); RemoteExitServer() { Thread t = new Thread(new Runnable() { @Override public void run() { waitForConnection(); } }); t.setDaemon(true); t.start(); } private void waitForConnection() { ServerSocket server = null; Socket socket = null; try { server = new ServerSocket(1234); socket = server.accept(); flag.set(true); } catch (IOException e) { e.printStackTrace(); } finally { if (server != null) { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } boolean shouldExit() { return flag.get(); } }
The client does just that: he opens the connection and nothing else
import java.io.IOException; import java.net.Socket; public class RemoteExitClient { public static void main(String[] args) { Socket socket = null; try { socket = new Socket("localhost", 1234); } catch (Exception e) { e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
The application is also very simple:
public class RemoteExitTest { public static void main(String[] args) { RemoteExitServer e = new RemoteExitServer(); while (!e.shouldExit()) { System.out.println("Working..."); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } System.out.println("done"); } }
(The code may be even more concise with try-with-resources, but that doesn't matter here)
Marco13
source share