Sankalp
Sankalp

Reputation: 173

How to terminate the Java process when the JAR has finished execution

I have a Java Program that does some web services call. i packed that program in a JAR file and placed it my linux machine. Then i made a .sh file the content of which were

#!/bin/sh 
. /etc/profile 
echo "The Script Starts now!!!!!!!!!!" 

export JAVA_HOME=/u01/app/oracle/java/java64/jrockit-jdk1.6.0_29 
export PATH=$JAVA_HOME/bin:$PATH 
cd /u01/CRM_PRD/stores/CRM_COC_Utility/Jars 

java -jar CRM_AccountCOC.jar 

echo "The Script ends now!!!!!!!!!!"

This sh file i have scheduled in cronjob to run after every 45 mins which means the above command is executed after every 45 mins.

The problem is when i do the TOP command say after a day or two, I can see multiple execution state of this JAR.Due to this the %CPU usage of my linux server has increased.

The JAR takes 10 mins to finish and the frequency to reexercute the JAR is after 45 mins. So what i need to do in my code or in sh file such that when this JAR has executed, the java process is also killed.

Hope it explained my issue.I am not much pro in linux and Java

Upvotes: 0

Views: 3059

Answers (2)

Michael Kazarian
Michael Kazarian

Reputation: 4462

write PID of your java process into file:

#!/bin/sh 
. /etc/profile 
echo "The Script Starts now!!!!!!!!!!" 

export JAVA_HOME=/u01/app/oracle/java/java64/jrockit-jdk1.6.0_29 
export PATH=$JAVA_HOME/bin:$PATH 
cd /u01/CRM_PRD/stores/CRM_COC_Utility/Jars 

java -jar CRM_AccountCOC.jar & # run jar as background process
echo $! > program.pid

echo "The Script ends now!!!!!!!!!!"

and kill it upon cron:

kill -9 `cat program.pid`

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117589

Basically, if all the non-daemon threads are finished, then the java application terminates. However, you can force it to terminate by:

System.exit(0);

Upvotes: 2

Related Questions