1

I have a Java worker that are polling a external queue system for jobs, through web service calls.

What is the most solid way to ensure that the worker is operating at any given time?

skaffman
  • 398,947
  • 96
  • 818
  • 769
dropson
  • 1,111
  • 2
  • 12
  • 23

2 Answers2

1

JVM execution is not different from any other program. So what you want to do is to put together a shell script and place it in /etc/init.d and link it appropriatelly to to /etc/rc.d. On RedHat flavors it will ensure service startup with the system.

Wring the script may be tricky, but I would copy one of existing ones and change it to call java executable with right parameters. In this script you would have to capture java process id. You can use it then to monitor your process and restart as necessary.

Alex Gitelman
  • 24,429
  • 7
  • 52
  • 49
  • Once I have the ability to control the application using it's PID, would then best way to ensure it's run state be by using a shell script added to CRON? Have it check if the current application PID is running and restart it if it's not? Any arguments against this? – dropson Jun 04 '11 at 20:59
  • 1
    Cron is a good choice to check if program died. Moreover,it can be used to start it as well. Just make script check if pid is present and process with it is running. If not start it. This way you can eliminate all this init.d complexity alltogether and can run jvm under your own user. – Alex Gitelman Jun 05 '11 at 00:55
0

The java.util.concurrent package offers a simple, solid framework for this kind of work.

Here's a simple example of some code that would work:

import java.util.concurrent.*;

public static void main(String[] args)
{
    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

    // Here's an anonymous class, but your should probably create a class for this
    Runnable poll = new Runnable()
    {
        public void run()
        {
            // put your polling code here
        }
    };

    // Have your code called every 5 seconds like this:
    service.scheduleAtFixedRate(poll, 0, 5, TimeUnit.SECONDS);
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722