Frage

In .NET, you can check the Environment.HasShutdownStarted property to see whether your service is being unloaded for whatever reason, and perform graceful unloading/cleanup.

So instead of:

while (true) { }

...you can use...

while (!Environment.HasShutdownStarted) { }

Is there an equivalent thing in Java?

War es hilfreich?

Lösung

Perhaps you're looking for a shutdown hook? This allows you to specify a thread to be run when the application is closed (as long as it's not brutally forced closed with kill -9 or similar, but in that case no environment can guarantee to do anything on shutdown.)

Runtime.getRuntime().addShutdownHook(new Thread() {

    public void run() {
        //Code here.
    }
});

From a practical perspective, you should also make these threads quick to execute - since otherwise the application will appear to hang upon exiting, and no-one likes that (plus, the OS or user may choose to kill off the application, aborting the hook at an arbitrary point.)

You can add multiple shutdown hooks, and they will be executed concurrently (and in an arbitrary order.)

Removal of shutdown hooks can be down in a similar way by calling removeShutdownHook().

Andere Tipps

You could add a shutdown hook. Basically registers an unstarted thread that will run when the application terminates.

Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() { 
      // logic for making a clean shutdown...
   }
})

The link above has a very good description of what happens during shutdown.

You can look at the shutdown hook API, and instead of doing

while(true) {
}

You can declare a member in your thread/runnable implementation to signify shutdown:

class MyRunnable implements Runnable {
    private running= false;

    public void setRunning(boolean running) {
        running= running;
    }

    public void run() {
        setRunning(true);
        while(running) {
            // do task
        }
    }
}

public static void main(String[] args) {
    final MyRunnable myRunnable= new MyRunnable();
    final Thread runThread= new Thread(myRunnable);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            myRunnable.setRunning(false);
        }
    });

    runThread.start();
    runThread.join();
}

This is not a perfect solution, but should get you at least in the right direction.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top