-1

I have code that should execute reasonably fast but occasionally may take long time to execute and produce a result. I'd like to limit the duration of that operation and abort it if it runs longer than a given time limit. I'd like the code to look like

Supplier<T> longRunningFoo = () -> {...}; // this may take a while to run
LongOpRunner runner = new LongOpRunner(longRunningFoo); // <-- some wrapper that limits operation duration

try {
    T result = runner.call(10000 /* ms */); // abort after 10000 milliseconds
} catch (LongOpTimeout e) {
    // handle timeout exception when "foo" gets aborted
}

Before I start writing my own I am interested to see if there are existing libraries that provide this capability.

oᴉɹǝɥɔ
  • 1,796
  • 1
  • 18
  • 31
  • Maybe you're looking for [this](https://stackoverflow.com/questions/2758612/executorservice-that-interrupts-tasks-after-a-timeout)? – Avi Oct 21 '19 at 16:55
  • Just a note: you won't get complete answer without specifying what type of workload lies under supplier, otherwise it would be hard to say how to abort it. If it's some kind of remote system, you may want to cancel running operation, invoking new one; if that's local computation, you'll need to ensure that Thread.interrupt() will propagate and so on. As for libraries, there's CompletableFuture, but timeout support is 9+, and it would be cumbersome to apply logic above. – Etki Oct 21 '19 at 16:55
  • In any case, a "do any libraries exist?" question is either too broad here, or off-topic. – Avi Oct 21 '19 at 16:57

2 Answers2

3

You can use Java provided built in Future where it provides the facility for timeout. See below the small code snippet.

ExecutorService ex = Executors.newSingleThreadExecutor();
    Future<?> future = ex.submit(new Runnable() {
        public void run() {
            try {
                //Do some long running operations
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Completed operation");
        }
    });
    Object someObject = future.get(10, TimeUnit.SECONDS);

You can also refer below the link for further reference.

Sambit
  • 7,625
  • 7
  • 34
  • 65
0

You can use ExecutorService.submit(Callable task) and then call Future.get(long timeout, TimeUnit unit) on the result.

Gustavo Passini
  • 2,348
  • 19
  • 25