Shahriar
Shahriar

Reputation: 824

running java jar files with script

I have a problem which I do not know how to solve. I have made a java polling app using executor service of 1 single thread. That service does some file manipulation and database interactions.

if we run with java -jar myapp.jar from command promt/ executable jar , it runs . We can stop it at any moment.

Now I need to make 2 scripts for the user (liek tomcat). One for start the app , another to stop.

But the think is when a user executes the script to stop, the process will not be killed until all the jobs/threads of executor service is finished. Because, if we kill the process while in running state, the system doing the job will stop can be in inconsistent state (during moving files for example ).

THe problem is, I can not access ExecutorService result from shell script.

How can I make two scripts to run this app and control and access the behaviors. ?

EDIT:

My myapp.jar runs a periodic executor service. I need to make a stop script which will allow to stop only after the executor service is not running the task, not kill the process. Because, if I kill the process during operation , I lost consistency of the system. My ssytem reads file and moves those into another directory. If I kill in the middle , some files will be processed,some will not. I need a solution where if user executes the stop script from the UNIX system, the script either does not kill the process or wait until the job finishes.

Upvotes: 0

Views: 693

Answers (1)

mtk
mtk

Reputation: 13717

I guess Shutdown Hook is the solution here which you need. Shutdown Hooks gives the user complete control over the thread upon which a shutdown action is executed. The thread can be created in the proper thread group, given the correct priority, context, and privileges, and so forth.

Sample program

public class ShutDownHook {

    public static void main(String[] args) {
        
        final Thread mainThread = Thread.currentThread();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                // Add your cleanup logic here
                System.out.println("Shutdown hook is executing");
                try {
                    mainThread.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        
        System.exit(0);
    }
}

Output

Shutdown hook is executing
  • Runtime.getRuntime().addShutdownHook(Thread h) adds the hook and
  • Runtime.getRuntime().removeShutdownHook(Thread h) remove the specified hook given as parameter.

You just need to add your proper code logic in the shutdown hook as specified above.

Reference link javadoc, One blog post

Upvotes: 1

Related Questions