Languages
[Edit]
EN

Java concurrency - avoid busy wait using ExecutorService and Future

7 points
Created by:
Yusef-Ewing
389

In this article we would like to show to to avoid busy wait in java using ExecutorService and Future.

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class TaskExecutorWithFuture {

    private final ExecutorService executor = Executors.newFixedThreadPool(2,
            new ThreadFactoryBuilder().setNameFormat("task-executor-%d").build()
    );

    private void executeTasks() throws InterruptedException, ExecutionException {

        Future<String> task1 = executor.submit(() -> {
            simulateTask(300);
            System.out.println(getThreadName() + " - Task 1 done");
            return "Results from task 1";
        });

        Future<String> task2 = executor.submit(() -> {
            simulateTask(100);
            System.out.println(getThreadName() + " - Task 2 done");
            return "Results from task 2";
        });

        System.out.println(getThreadName() + " - waiting for 2 tasks to be completed");
        String result1 = task1.get();
        String result2 = task2.get();
        System.out.println(getThreadName() + " - 2 tasks done");

        executor.shutdown();
    }

    private String getThreadName() {
        return Thread.currentThread().getName();
    }

    private void simulateTask(int timeout) {
        sleep(timeout);
    }

    private void sleep(int timeout) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        new TaskExecutorWithFuture().executeTasks();
    }
}

Output:

main - waiting for 2 tasks to be completed
task-executor-1 - Task 2 done
task-executor-0 - Task 1 done
main - 2 tasks done

 

See also

  1. What is busy waiting lock?

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java concurrency

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join