aryakdangol
aryakdangol

Reputation: 23

CompletableFuture run task in a non-blocking way with limited threads in JAVA

I have defined a pool of 2 threads like this:

Executor executor = Executors.newFixedThreadPool(2);

Now I have three tasks, two of which are blocking and one which is non-blocking.

CompletableFuture<Integer> blocking1 = CompletableFuture.supplyAsync(callableTask1, executor);
CompletableFuture<Integer>blocking2 = CompletableFuture.supplyAsync(callableTask2, executor);

CompletableFuture<Void> nonBlocking = CompletableFuture.runAsync(() -> {
    System.out.println("nonBlocking task's thread:  " + Thread.currentThread());
    System.out.println("Non Blocking task");
});

Both callableTask1 and callableTask2 are blocking as it makes the thread wait. Currently, to print "Non-Blocking task" it is waiting for any of the blocking task to free up the thread. I want any thread to not wait for any of the task to finish and process nonBlocking task immediately.

The output should be:

"Non Blocking Task" -> first
"callable Task1" or "callable Task2" -> second

Upvotes: 0

Views: 161

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 339837

Another executor service

If some tasks are holding up pressing tasks, create another executor service.

Executor executorPooled = Executors.newFixedThreadPool(2);
Executor executorPriority = Executors.newSingleThreadExecutor();

Upvotes: 0

Related Questions