As part of the development that I am developing, the user can choose to perform a specific time task in the background while doing something else. This task computes a series of results. At some point, when he needs the results of a background task, it is acceptable to wait some more time until:
a) a timeout occurs (in this case, the user would like to get all the results calculated so far, if they exist); or
b) the maximum number or calculated results are achieved (normal completion),
whichever comes first.
Launched: Even if a timeout occurs, the user still needs the results calculated so far.
I tried to do this using the Future<V>.get(long timeout, TimeUnit unit) and Callable<V> -derived class, but it happens that when a Timeout exception occurs, it usually means that the task was prematurely completed, so the results are not available . Thus, I had to add the getPartialResults() method (see DiscoveryTask below), and I am afraid that this use is too inconsistent for potential users.
Discovery call:
public Set<ResourceId> discover(Integer max, long timeout, TimeUnit unit) throws DiscoveryException { DiscoveryTask task = new DiscoveryTask(max); Future<Set<ResourceId>> future = taskExec.submit(task); doSomethingElse(); try { return future.get(timeout, unit); } catch (CancellationException e) { LOG.debug("Discovery cancelled.", e); } catch (ExecutionException e) { throw new DiscoveryException("Discovery failed to execute.", e); } catch (InterruptedException e) { LOG.debug("Discovery interrupted.", e); } catch (TimeoutException e) { LOG.debug("Discovery time-out."); } catch (Exception e) { throw new DiscoveryException("Discovery failed unexpectedly.", e); } finally {
Detection Implementation:
public class DiscoveryTask extends Callable<Set<ResourceId>> implements DiscoveryListener { private final DiscoveryService discoveryService; private final Set<ResourceId> results; private final CountDownLatch doneSignal; private final MaximumLimit counter;
In chapter 6 of the Java Concurrency book in practice by Brian Goetz et al., The authors show a solution to a related problem, but in this case all the results can be calculated in parallel, which is not my case. To be precise, my results depend on external sources, so I don’t I can control when they come. My user determines the desired maximum number of results that he wants before calling the task, and the maximum time limit that she agreed to wait after she is ready to receive the results.
This is normal? Would you do it differently? Is there a better approach?