merlin2011
merlin2011

Reputation: 75619

What is a clean / recommended way to terminate a perpetually-running command-line Java application?

More specifically, I have a multithreaded command line Java application which runs and collects data until the user terminates it.

The obvious way for the user to terminate it is by pushing Control-C, but then I need to install a shutdown hook in the VM and deal with all the threads.

Is there a nicer / more appropriate way for the user to inform the application that it's time to shutdown?

For example, is there a way to capture some other key combination and set a boolean flag in my application?

As a further clarification, I seek something functionally similar to signal handling in C.

Upvotes: 3

Views: 545

Answers (4)

Dead Programmer
Dead Programmer

Reputation: 12585

Is there a nicer / more appropriate way for the user to inform the application that it's time to shutdown?

The best way is to use Java Monitoring and Management

Look at this post for example.

It is best not to rely on shutdown hook.Shutdown hook in java works for KILL -15 AND KILL and do not work for KILL -9 (HARD KILL)

Upvotes: 1

anubhava
anubhava

Reputation: 786001

Consider using shutdown hook like this:

Runtime.getRuntime().addShutdownHook(shutdownHook);

to have your own code that runs whenever the JVM terminates under 1 of the following conditions:

  1. The program exits normally, such as when the last non-daemon thread exits or when the Runtime.exit() method is invoked.
  2. The virtual machine is terminated in response to a user interrupt, such as typing CTRL-C, or a system-wide event, such as user logoff or system shutdown (for example, the JVM receives one of the interrupt signals SIGHUP (Unix Only), SIGINT, or SIGTERM).

You can refer to: http://www.ibm.com/developerworks/ibm/library/i-signalhandling/ for more details (Disclaimer: very old article pertains to JDK 1.3.1)

Upvotes: 1

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72835

This is not a Java specific solution but (atleast on Linux) during shutdown, the operating system sends a SIGTERM to all processes (following by a SIGKILL after a grace period). Your application should install a handler for this and then shutdown gracefully. Once you do this, it will automatically take care of itself when you shutdown your VM.

Upvotes: 0

Manish
Manish

Reputation: 3968

One way can be to create a new thread which will "listen" to standard input. Based on whatever key pattern you decide, that thread can set the flag in the main application.

Upvotes: 2

Related Questions