0

I would like to stop a running Java-program in a controlled way.

I have started the program with a bash-script called with crontab and it runs on a Ubuntu server.

I want the Java-program to exit in a controlled way so not kill it.

I can't have an input-console and make it listen to a socket and send a packet to that socket to make it stop seems to much work and hard to do locally on the server.

Is there some other approach I can take on this problem?

John Master
  • 309
  • 1
  • 4
  • 18
  • 1
    I would suggest to use a socket and send a packet. When the program recieves the packet it will initiate its shutdown routine. – Anubian Noob Apr 17 '14 at 15:51
  • possible duplicate of [How to stop java process gracefully?](http://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully) – endriu_l Apr 17 '14 at 15:56
  • Listening to a socket and getting commands from it is a really piece of cake in java. So it might be the least trouble. – azgar Apr 17 '14 at 15:57
  • See this question http://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully . Shutdown hooks + standard kill is the way to go, tested on production :) – endriu_l Apr 17 '14 at 15:57
  • A related answer [Determine if an application is shutting down normally](http://stackoverflow.com/a/6214223/697630). – Edwin Dalorzo Apr 17 '14 at 16:07
  • For me it would be best if I could control the program from a web page on the server (Apache), not sure if that is possible. I have looked into [Java Management](http://docs.oracle.com/javase/1.5.0/docs/guide/management/overview.html) as an alternative, but I leaning towards listening on socket. – John Master Apr 18 '14 at 14:09

3 Answers3

0

What You could do is create some kind of marker and poll it periodically. For instance, create a temporary file and act if it gets deleted. Or created. Or gets some magic cookie written in it. Or You might spawn a subprocess and work until that gets killed. There is some discussion on catching UNIX signals in Java, but I never dug into it.

azgar
  • 93
  • 6
0

Best way to indicate a java process to kill itself is

Create a flag in a config file or database field such as

kill = false

Create a thread in your java process which polls on this config variable every second.

Once the flag is set to kill the process such as

kill=true

You can release all the resources and exit.

Uday Shankar
  • 844
  • 7
  • 20
-1

I don't know if this is usefull for your purposes but you can call System.exit(1); when you want to stop a Java program; e.g. when user clicks on a button you call System.exit(1); in your Java code

Angelo

Angelo Immediata
  • 6,635
  • 4
  • 33
  • 65