1

I use the ScheduledExecutorService to execute a task at a fixed rate. Here is the contents of my main method:

RemoteSync updater = new RemoteSync(config);
try  {
    updater.initialise();
    updater.startService(totalTime, TimeUnit.MINUTES);
} catch (Exception e) {
    e.printStackTrace();
}

RemoteSync implements the AutoCloseable (and Runnable) interface, so I initially used try-with-resources, like this:

try (RemoteSync updater = new RemoteSync(config)) {
    ...
} catch (Exception e) {
   e.printStackTrace();
}

But updater.startService() returns immediately after scheduling the task, so the updater.close() is called prematurely and the application exits.

Here is the startService() method of RemoteSync:

public void startService(int rate, TimeUnit unit) {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    service =
        scheduledExecutorService.scheduleWithFixedDelay(this, 1L,
        rate,
        unit);
}

Ideally, I would like to have a method like:

scheduledExecutorService.executeAtTermination(Runnable task)

This will allow me to call close() when scheduler has actually stopped, unfortunately I am not aware of such a method.

What I can do, is block the startService() method, with something like this:

while (!scheduledExecutorService.isTerminated()) {
    Thread.sleep(10000);
}

but this feels dirty and hackish.

Any suggestion are welcome.

Ian2thedv
  • 2,691
  • 2
  • 26
  • 47
  • maybe you can use application shutdown hook. Like in [this](http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java) discussion. – nukie May 07 '15 at 12:41
  • Hmm, I've heard about shutdown hooks. I'll give it a go. Thanks @nukie – Ian2thedv May 07 '15 at 12:48
  • @nukie I ended up using a shutdown hook, if you care to add an answer I will accept. – Ian2thedv May 13 '15 at 08:26

2 Answers2

1

Maybe you can use application shutdown hook. Like in this discussion.

You can add code like this in some stage of application initialization:

Runtime.getRuntime().addShutdownHook(new Thread() {
  public void run() {
    >>> shutdown your service here <<<
  }
});
Community
  • 1
  • 1
nukie
  • 691
  • 7
  • 14
0

You can try scheduledExecutorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS), possibly in a separate thread

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Seems like a good option, only problem is there is no set timeout. The application may run for days or even weeks. What I can, is check if the service has been terminated. If not (timeout occurred), I can just call `awaitTermination` again. Thanks for the suggestion though. – Ian2thedv May 07 '15 at 13:08