Doc Davluz
Doc Davluz

Reputation: 4250

How to propagate timeout from one FutureTask to another dependent one used by its Callable?

I am in the following situation (perhaps I have overengineered the whole thing or I am in a complete deadlock, but cannot think to another way of doing that):

Hereunder, the state of code I achieve so far:

I have imagined passing by introspection to alter private inner sync field of FutureTask with my hand-made Callable in my custom get method, but introspection and reflection are generally avoidable hacks.

Upvotes: 1

Views: 203

Answers (1)

axtavt
axtavt

Reputation: 242686

If you use Guava, it looks like a good case for ListenableFutures:

List<ListenableFuture<Object>> requiredTasks = ...;

ListenableFuture<List<Object>> requiredTasksResult = Futures.allAsList(requiredTasks);

ListenableFuture<Object> resultFuture = Futures.transform(requiredTasksResult, new Function<List<Object>, Object>() {
    public Object apply(List<Object> results) {
        // Apply computing formula
    }
}, threadPool); // Function will be executed in threadPool

Object result = resultFuture.get(10, TimeUnit.SECONDS);

You can get ListenableFuture for FutureTask by submitting it to ListeningExecutorService, or by using ListenableFutureTask instead.

Upvotes: 3

Related Questions