Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice for Returning Java Future from Library

Tags:

java

future

I am working on a Java library that implements the Jump Point Search algorithm. There are two exposed methods you can call to run the search. A synchronous one and one that returns a Java Future of the results.

public Future<Queue<T>> findPath(T start, T goal) {
    FutureTask<Queue<T>> future = new FutureTask<>(() -> findPathSync(start, goal));
    future.run();
    return future;
}

What I would like to know is, what is the best practice in this case. Should the library actually run the FutureTask and return the Future, or should it return a FutureTask and the end user would have to know that the Task has not actually been executed yet?

Thanks!

like image 214
Kevin Sheehan Avatar asked Sep 27 '22 17:09

Kevin Sheehan


1 Answers

I can't really speak for a "best practice" but, as a user, if I call a method my default assumption is that it's triggered something - that it's initiated execution - and usually the "construct only" paradigm is reserved for the builder pattern or a factory.

So the above code you have is the behaviour I would expect, and what I feel I see most often if not always, even in other systems (i.e. Node.js)

like image 79
Doug Moscrop Avatar answered Oct 20 '22 18:10

Doug Moscrop