EN
Java concurrency - avoid busy wait using ExecutorService and Future
7 points
In this article we would like to show to to avoid busy wait in java using ExecutorService and Future.
xxxxxxxxxx
1
import com.google.common.util.concurrent.ThreadFactoryBuilder;
2
3
import java.util.concurrent.ExecutionException;
4
import java.util.concurrent.ExecutorService;
5
import java.util.concurrent.Executors;
6
import java.util.concurrent.Future;
7
import java.util.concurrent.TimeUnit;
8
9
public class TaskExecutorWithFuture {
10
11
private final ExecutorService executor = Executors.newFixedThreadPool(2,
12
new ThreadFactoryBuilder().setNameFormat("task-executor-%d").build()
13
);
14
15
private void executeTasks() throws InterruptedException, ExecutionException {
16
17
Future<String> task1 = executor.submit(() -> {
18
simulateTask(300);
19
System.out.println(getThreadName() + " - Task 1 done");
20
return "Results from task 1";
21
});
22
23
Future<String> task2 = executor.submit(() -> {
24
simulateTask(100);
25
System.out.println(getThreadName() + " - Task 2 done");
26
return "Results from task 2";
27
});
28
29
System.out.println(getThreadName() + " - waiting for 2 tasks to be completed");
30
String result1 = task1.get();
31
String result2 = task2.get();
32
System.out.println(getThreadName() + " - 2 tasks done");
33
34
executor.shutdown();
35
}
36
37
private String getThreadName() {
38
return Thread.currentThread().getName();
39
}
40
41
private void simulateTask(int timeout) {
42
sleep(timeout);
43
}
44
45
private void sleep(int timeout) {
46
try {
47
TimeUnit.MILLISECONDS.sleep(timeout);
48
} catch (InterruptedException e) {
49
e.printStackTrace();
50
}
51
}
52
53
public static void main(String[] args) throws InterruptedException, ExecutionException {
54
new TaskExecutorWithFuture().executeTasks();
55
}
56
}
Output:
xxxxxxxxxx
1
main - waiting for 2 tasks to be completed
2
task-executor-1 - Task 2 done
3
task-executor-0 - Task 1 done
4
main - 2 tasks done