The only way to get a Future
, from what I understand, is to use an ExecutorService
, which is obtained for instance via Executors.newFixedThreadPool(10)
(btw, how do you how many threads to use? is there some thumb rule?).
So what I don't understand, is whether am I supposed to use:
ExecutorService executorService = Executors.newFixedThreadPool(n);
And then save it (e.g. in some top level IoC
) and call the executorService
whenever I need new Future
?
Isn't there like a default Java's built-in ExecutorService
I can used, thus avoiding the nag of ExecutorService
initialization and maintenance?
An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor. execute(java. lang.
Using shutdown() and awaitTermination() In general, the ExecutorService will not be automatically destroyed when there is no task to process. It will stay alive and wait for new tasks to come. It simply means that JVM will not terminate if we are expecting it to.
Here is a code example: ExecutorService executorService = Executors. newSingleThreadExecutor(); Set<Callable<String>> callables = new HashSet<Callable<String>>(); callables. add(new Callable<String>() { public String call() throws Exception { return "Task 1"; } }); callables.
When one submit a task to ExecutorService which is take a long running time, then it returns a Future object immediately. This Future object can be used for task completion and getting result of computation.
default Java's built-in ExecutorService
ForkJoinPool.commonPool() - Returns the common pool instance. This pool is statically constructed; its run state is unaffected by attempts to shutdown() or shutdownNow(). However this pool and any ongoing processing are automatically terminated upon program System.exit(int)...
Future<?> future = ForkJoinPool.commonPool().submit(() -> { /* something to do */}) ;
But there is a more modern way: CompletableFuture
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { /* something to do */});
Isn't there like a default Java's built-in ExecutorService I can use...?
There is in Java8.
Read the Javadoc for java.util.concurrent.CompletableFuture.supplyAsync(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With