I have a shell script which is used to launch the java application.Shell script has following commands in it to launch the class which contain main method :
_MainJava="com.abc.launchers.AgentLauncher"
_ConfigFilePath="/home/lego/ConfigProperties"
_LogFilePath="/home/lego/Logs/"
java -jar "${_MainJava}" "${_ConfigFilePath}" "${_LogFilePath}"
I launch this script through command prompt.
Java code has a JMS listener which is always in listening mode .So this java code is always up and never terminates.
Now I want to terminate this java program.One way is (and which I do every time) is terminate by pressing "Cntrl+c" which is killing the program by force and this way I cannot print logs like, "Terminating agent".
If I know in advance that agent will be terminated(like some condition),I can print the logs and do System.exit(0). But I cannot know this in advance as agent will only be terminated during maintenance time.
Please help me to understand how can I achieve this.
As suuggested in comment section ,shutdown hook is the perfect option. Now I have been trying to implement it in my test code.My code is like following :
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println("Shutdown Hook is running !");
}
});
System.out.println("Application Terminating ...");
while(true) {
System.out.println("Running");
}
}
In eclipse IDE, I go in debug tab where I see this code running continuously ,I do right click -> terminate and it doesn't print anything.
Final output :
Running Running Running . . . .