How do I stop a daemon thread that does scheduled database backup ? - java

I've written a very simple command line programme that uses mysqldump to dump data at a specified interval. I wanted it to be running after I run the programme and I disconnect putty ssh connection.
But as soon as I exit the ssh connection, the programme shuts down.
I think I can make my programme run even after I disconnected from the ssh by using daemon threads but I'm worried about not being able to find and stop unnecessary duplicate daemon threads.
The scenario I'm decribing is...
1. I log into the server using putty.
2. Turn on the auto backup programme.
3. I exit the putty connection.
---the daemon is running
4. Hopefully, when I log into the server again, I have a way to stop the auto backup programme if needed.
Cron jobs and DBMS specific methods are out of my options. I'd like to learn how to do the job described above and use it where ever the situation fits not just database backup.
Any good ideas ? : )

In short, you have to launch your program in a special way, and you have (at least) two options: nohup or screen.
Let's now discuss why and how each one works.
nohup
Java's daemon threads is not what you are looking for, they have nothing to do with the issue. You can use normal threads (or even a single-threaded java program). You just need to change the way you launch your java program.
I have many executable jars that run as "daemons" on a bunch of servers, and I made a simple launch script that prepares the environment and makes it possible to terminate the SSH connection without stopping it. The main part is how to invoke the JVM: you use nohup.
nohup java -jar myfile.jar > stdout.log &
From nohup's man,
nohup - run a command immune to hangups, with output to a non-tty
So, when you terminate your SSH connection, it will send SIGHUP to all processes it started which would terminate them as you are observing. With nohup, however, your process is immune to it.
Also, note that I redirect the standard output to a file called stdout.log. This is done so that you can see whatever your program writes to STDOUT (generally some logging information that would be useful for debugging).
To terminate your program, you can use jps to list the PID of your process (say it's 123), then call kill 123. Note that for this to work your program needs to correctly handle this kind of shutdown (which involves adding a shutdown hook with Runtime.getRuntime().addShutdownHook(...) which will terminate all the threads you launched).
If, for whatever reason (a bug, or you didn't implement a graceful shutdown), the program won't terminate after issuing the kill command (which sends the process a SIGTERM), you can change the signal it sends to SIGKILL with kill -9 123, which will simply destroy the process. Mind that this can be as dangerous as a power failure (ie, suppose you are in the middle of the try block of a try {} finally {} -- your finally block will not execute!).
screen
There's an alternative, which is to use SCREEN. With it, you launch a shell that is also immune to shutdowns, and that you can share among many connections. To use it, connect to your server, and then:
screen -R
A new shell will start, in which you run your java program as normal:
java -jar myfile.jar
To make it go to the background, just press ctrl+a ctrl+d. To bring it back to the front, just execute screen -R again. If you wish to terminate your program, you could do so by entering the screen session again and pressing ctrl+c (if your java program correctly deals with this kind of shutdown).

Two possibilities for scheduled tasks, in order from least to most complex, are the TimerTask and the Quartz Scheduler. Both offer the option to cancel/delete the scheduled job.

Related

How can I ensure all Java threads die

I am writing a multithreaded Java program, which I will run from the command prompt. It's got both a gui (javafx) and a lot of background threads. If I hit Ctrl+C from the command prompt that I started the program with, it asks "Terminate Batch job? Y/N" and I hit Y and then I'm simply returned to the prompt. However - I am wondering if there by any chance might still be running any background threads that weren't terminated gracefully?
Your "main" code and all the threads run in JVM. If you terminate JVM (as process) then everything running in it will be terminated as well.
More on "catching" ctrl+c: Catching Ctrl+C in Java
As far as I know, there's no way to "catch" or "intercept" Ctrl+C "event" from the command line, so your can't really tell if there are any unfinished threads and end them gracefully. (disappointing, I know).

Stopping a daemon thread on the AS400 using QShell

I have a java program which I start with the comman java -jar MyProgram.jar, and I can stop the java program using the command java -jar MyProgram.jar stop. I am having trouble running my command in the same shell because the previous program is running, is there another way to open another QShell or a way to run another command in the same shell?
Qsh does not support job control, and you can only open one for each session.
The easiest is to open yet another green screen session and run a second qsh inthere
Note that typing SysReq-2 stops the current program, too.
A daemon is presumably intended to be a long-running background service. As such, you would normally be submitting this to run in a some batch subsystem. You would normally use ENDJOB on it from another session.
See your system administrator for details on where they want your job to run on this particular system. There are various options, and testing may be different than how they wish it to run in production.

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.
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.
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:
The program exits normally, such as when the last non-daemon thread exits or when the Runtime.exit() method is invoked.
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)
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)
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.

i want to continously run my java threads

I am running my java application where i have used threads...
i am running this application using ant command on the terminal..
But when i close my terminal or press ctrl+c,then java program which was running stops...
Please help me out to solve this as i want to run this program continously...
If you kill the Java process, Java will no longer be running. If you want the threads to keep running continuously, the Java program must remain active.
Invoking such a program with ant is not usually the way to do it. On Unix-like systems, you would typically run such a program in the background via /etc/init.d startup scripts. In Windows the equivalent would be starting your program as a service, though I'm not sure of the intricacies involved in getting Java to run this way.
If you're running something from a concole - how about just not killing it and minimising the console? If you're starting it from Linux (or Cygwin) just append a & to the end of the command line and the process will run in the background.
Tell us more about your environment, and what compromises you're prepared to put up with (e.g. having a minimised console window sit in the taskbar) and we can help you more. At the moment, the only definitive answer I can give is that "yes - Ctrl-C will kill your program (as intended). If you want it to keep running, don't tell it to stop running." :-)
You can run your application as a service in linux or windows.
Have a look at the screen command for Linux.
I guess this is desired behavior. If you terminate your application, It gets shut down.
If you wish to run the application in the background you should consider making it a windows service or a deamon.
If you wish to continue running it as a application on *nix, you can consider to use GNU Screen.
Run the ant command in the background and redirect its output to a file:
ant &> my.log &.
NB: this issue does not seems thread related (unless I've misunderstood it).
It sounds like you want to daemonize your ant task. I'd suggest the following command:
nohup ant &> ant.log < /dev/null &
The nohup will allow the program to continue to run after you close the terminal.
I'm surprised nobody has mentioned the all-too-famous Java Service Wrapper. This is an excellent piece of software if you are developing long-running processes (a.k.a services).

How do I kill processes in Java without forcing it?

I have a Java program that runs a number of other programs. Once the user is finished they have a button to kill all processes, this should kill everything that is running but it should do it with forcing them. At least one of these other processes is also written in Java and has a number of shutdown hooks as it automatically saves a preferences file on exit and kills processes it has started itself, such as.
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if (process != null)
process.destroy();
}
}
When the main process calls destroy the above code is not run on the subprocess. Is there anyway that I can terminate the processes so this will still run?
I am porting from Perl which does it will the kill(9,#kill_process);
Thanks.
Kill signal 9 (SIGKILL) tells the operating system to kill the process. The process gets no notification in advance that this is going to happen and cannot do any cleanup because of it.
process.destroy() is the equivalent of Perl's kill(9,#kill_process);, and your old process wouldn't have been doing any cleanup either.
Kill signal 15 (SIGTERM) will tell a process to kill itself.
There are couple of ways how to communicate with application. One of the most common is send signal. Command for signal is called kill. Perl code you post use this aproach.
You can send various signals, some of them are handled by application some of them are handled by os.
Default signal is HUP. It tell application that "connection to user" was terminated (it actually mean modem hanged ) and it should exit. Nicely behaving application will exit.
If you send signal 9 (this is what your perl code does), OS will terminate application without question.
Another approach is to communicate with application using its default way. So you can send "Ctrl+c" or "Alt+f4" (those are commands with usually end application) to STDIN of the process.

Categories