Java Shutdown function not executing - java

Within the main() of my application I have the following code to back up data so it doesn't get lost in the event of a system shut down.
//add hook to trigger Production Shutdown sequence
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
Production.shutdown();
}
}));
However, whether I press the Stop button in my IDE or rely on input via the log (code shown below) it never seems to save data to the database or write any logs to the console.
ctx.deploy(server);
server.start();
//start the production process
Production.init();
System.in.read();
server.stop();
How come this shutdown function is not being executed?

You need to use the Exit button, not Stop, see my answer here for more details.
Note that this feature is currently available only in Run mode, not in Debug.

System.exit(0)
add this line in your code. Debug from here onwards

Related

Java shutdown hook not running

I have a product service in Java. In our code I am creating shut down hook, but when I stop service it is not calling shut down hook consistently. Out of 5 stop calls it has called shutdown hook only once.
Runnable shutdownHandler = new Runnable() {
#Override
public void run() {
s_log.info("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
Can anybody please tell me what could be the reason behind this not getting called consistently?
Check the following code:
Runnable shutdownHandler = new Runnable() {
#Override
public void run() {
System.out.println("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
and if it gives you expected output, you need to check the documentation of your logging framework.
I am also finding that my framework (Jooby) and Java shutdown hooks work fine on my Mac on IntelliJ which sends a kill SIGINT (-2) however on Ubuntu Server 20.04 LTS they don't run.
As my Java app is a webapp I came up with a simple workaround:
Setup a controller to listen to some url that isn't easily guessable e.g.
/exit/fuuzfhuaBFDUWYEGLI823y82941u9y47t3u45
Have the controller simply do the following:
System.exit(0)
Do a curl or wget from a script to the URL and the shutdown hooks all fire as JVM comes down.
I suspect for some reason on Linux there is a bug and no matter what interrupt that I use besides SIGKILL they all effectively behave like SIGKILL and the JVM comes down hard/abruptly.

Java Shutdown hook is getting called without exitVM.0 from permission.getName()

In my application I have written the shut down hook. But some third party code is calling that shut down hook.
This shut down hook should not be called by any third party code.
I have written the code to block shut down hook by third party but it did not help. (This code worked in my standalone test program. but did not worked in my application.)
Below are the code where something different behaviour is occurring:
final SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
System.out.println("In checkPermission:{" + permission.getName() + "}");
if ("exitVM.0".equals(permission.getName())) {
throw new ExitTrappedException();
}
}
};
When I execute this code in Test program then when shut down being called its giving me "In checkPermission:{exitVM.0}". So that it comes in if condition and my shut down hook gets blocked.
Now when I tried same thing in my application then this "exitVM.0" is not getting printed and shut down hook is getting called.
Any suggestions? Is there any different permission.getName() which can call shutdown hook?
It could be exitVM.1, exitVM.2, etc, since the number is just the shutdown code. The actual permission is called exitVM. (see http://docs.oracle.com/javase/7/docs/technotes/guides/security/permissions.html). So you could use permission.getName().startsWith("exitVM").
But what you're trying to do (prevent application being shut down) sounds like it might not be the best idea. What's the context?

Schedule a executable file without Windows task scheduler

Is it possible to schedule a executable file to run just before log-off using java?
I am working on a application that needed to send a message to the sever just before the system log-off/shutdown. But I didn't find any method to solve it. If anyone know plz help me.
Thanks in advnce.
As stated in the comments a ShutdownHook is probably what you are searching for.
Short example:
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
// Code to be executed when JVM exits
System.out.println("JVM exit");
}
});
Note that the ShutdownHook will execute whenever the JVM exits. So it will also execute when your program terminates normally.
If you have any further questions comment on this answer.

Shutdown hook from UNIX

I am trying to get my Java program to exit gracefully on my unix server. I have a jar file, which I start through a cron job in the morning. Then in the evening, when I want to shut it down, I have a cron job which calls a script that finds the PID and calls kill -9 <PID>. However, it doesn't seem that my shutdown hook is activated when I terminate this way. I also tried kill <PID> (no -9) and I get the same problem. How can I make sure the shutdown hook gets called? Alternatively, perhaps there is a better way to kill my process daily.
class ShutdownHook {
ShutdownHook() {}
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Shut down hook activating");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
You can use code like this on Unix to trap SIGINT (#2) signal:
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
// Forced exit
System.exit(1);
}
});
kill -9 <pid> sends a KILL signal. This signal cannot be intercepted by the program.
If you call kill <pid>, the TERM signal (15) wil be sent. In that case, the JVM will catch the signal and the shutdown hooks will be executed.
This has nothing to do with the signals the JVM is trapping/receiving but everything to do with the terrible shutdown process of Gnome, which apparently needs to be cooperative not to absolutely shit the bed (and the jdk doesn't have the api for this). If you want to see a even worse consequence of this, try to run:
dbus-monitor --profile --session type='method_call',interface='org.gnome.SessionManager'
on a shell, and logout or restart: it will crash gnome-shell and hang the computer until you login on a TTY and order a restart.
Maybe kdbus will fix this on this case, maybe not. The only thing i know is that shutdownhooks on a java application that is using AWT (not command line) will NEVER run its shutdownhooks on GNOME3. Actually, the VM will always exit with non-zero code (failure) presumably from native code. At least it doesn't hang, although this makes shutdown hooks quite useless
(i've been trying to make a workaround by using dbus-monitor, but as you can see from the example i gave, it's a bit too dangerous too).

Application continues to run after System.exit(0) is called - Java

I'm trying to clean up resources in my application before it shuts down, following on from my previous question (Detecting When A Java Application Closes) I have implemented the following code which performs the cleanup operation perfectly.
//Intercept when the application closes
Runtime.getRuntime().addShutdownHook(new Thread()
{
#Override
public void run()
{
//Reclaim resources from MIDI usage
if(_midiInstance.CleanUp())
{
Logger.Add("Closed resources successfully on ShutDown");
}
else
{
Logger.Add("Failed to close all resources on ShutDown");
}
System.exit(0);
}
});
Although the System.exit(0); call is understood and processed the application continues to run, just without a visiable GUI. I've thought about placing the System.exit(0) call just outside of the Thread but then it's out of scope, there aren't any other threads or streams running.
Is there an additional step I need to take when hooking in to the ShutDown event to ensure everything closes?
Thanks for your time, I greatly appreciate it.
After reading your other question, it seems like your are probably not calling dispose() on your window(s). If true, that would explain the cause of your problem.
You need to over ride the windows close button:
//overriding the windowClosing() method will allow the user to click the close button
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
By doing this the program will close not just become invisible.

Categories

Resources