Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a default ExecutorService or am I doomed to create one and maintain it to get Future objetcs?

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?

like image 937
Tar Avatar asked May 20 '16 10:05

Tar


People also ask

Do we need to close ExecutorService?

An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor. execute(java. lang.

What happens if we don't shut down ExecutorService?

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.

Can you give an example for ExecutorService?

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.

What is a Future How is it used in ExecutorService?

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.


2 Answers

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 */});
like image 153
Dmitry Sokolyuk Avatar answered Oct 21 '22 18:10

Dmitry Sokolyuk


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(...).

like image 44
Solomon Slow Avatar answered Oct 21 '22 19:10

Solomon Slow