Master the Executor framework, ExecutorService, ScheduledExecutorService, thread pools, Future, CompletableFuture, and concurrent API for the OCP 21 exam.
Table of Contents
1. Executor Framework
The Executor framework provides a higher-level replacement for working with threads directly. It manages thread creation and lifecycle.
1.1 Executor Interface
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Task executed"));
// Executor interface has one method: execute(Runnable)
2. ExecutorService
ExecutorService extends Executor and provides methods for managing task execution and shutdown.
2.1 Submitting Tasks
ExecutorService executor = Executors.newFixedThreadPool(5);
// Submit Runnable
Future<?> future1 = executor.submit(() -> System.out.println("Task 1"));
// Submit Callable
Future<Integer> future2 = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
// Shutdown
executor.shutdown(); // Graceful shutdown
// executor.shutdownNow(); // Force shutdown
3. Thread Pools
3.1 Common Thread Pool Types
// Fixed thread pool
ExecutorService fixed = Executors.newFixedThreadPool(10);
// Cached thread pool (creates threads as needed)
ExecutorService cached = Executors.newCachedThreadPool();
// Single thread executor
ExecutorService single = Executors.newSingleThreadExecutor();
// Virtual thread executor (Java 21)
ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor();
// Work stealing pool (ForkJoinPool)
ExecutorService workStealing = Executors.newWorkStealingPool();
4. Future Interface
Future represents the result of an asynchronous computation.
4.1 Using Future
ExecutorService executor = Executors.newFixedThreadPool(5);
Future<Integer> future = executor.submit(() -> {
Thread.sleep(2000);
return 100;
});
// Check if done
boolean done = future.isDone();
// Get result (blocks until available)
try {
Integer result = future.get(); // Blocks
Integer result2 = future.get(1, TimeUnit.SECONDS); // Timeout
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
// Cancel task
boolean cancelled = future.cancel(true); // true = interrupt if running
5. CompletableFuture
CompletableFuture (Java 8+) provides a more flexible way to work with asynchronous computations, supporting chaining and composition.
5.1 Creating CompletableFuture
// Create completed future
CompletableFuture<String> completed = CompletableFuture.completedFuture("Done");
// Create and complete asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Result";
});
// Run asynchronously (no return value)
CompletableFuture<Void> runFuture = CompletableFuture.runAsync(() -> {
System.out.println("Running");
});
5.2 Chaining Operations
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenApply(String::toUpperCase)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "!"));
String result = future.get(); // "HELLO WORLD!"
// Combining futures
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combined = future1.thenCombine(future2, (a, b) -> a + " " + b);
6. ScheduledExecutorService
ScheduledExecutorService extends ExecutorService and supports scheduling tasks for execution at a future time.
6.1 Scheduling Tasks
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
// Schedule once after delay
ScheduledFuture<?> future1 = scheduler.schedule(() -> {
System.out.println("Delayed task");
}, 5, TimeUnit.SECONDS);
// Schedule at fixed rate
ScheduledFuture<?> future2 = scheduler.scheduleAtFixedRate(() -> {
System.out.println("Fixed rate task");
}, 0, 1, TimeUnit.SECONDS);
// Schedule with fixed delay
ScheduledFuture<?> future3 = scheduler.scheduleWithFixedDelay(() -> {
System.out.println("Fixed delay task");
}, 0, 1, TimeUnit.SECONDS);
7. Exam Key Points
Critical Concepts for OCP 21 Exam:
- Executor: Interface for executing tasks
- ExecutorService: Extends Executor, manages task lifecycle
- Thread Pools: newFixedThreadPool(), newCachedThreadPool(), newSingleThreadExecutor()
- Virtual Threads: newVirtualThreadPerTaskExecutor() (Java 21)
- Future: Represents asynchronous computation result
- get(): Blocks until result is available
- CompletableFuture: More flexible than Future, supports chaining
- thenApply(): Transform result of CompletableFuture
- thenCompose(): Chain CompletableFutures
- thenCombine(): Combine two CompletableFutures
- ScheduledExecutorService: Schedule tasks for future execution
- scheduleAtFixedRate(): Execute at fixed intervals
- scheduleWithFixedDelay(): Execute with fixed delay between executions
- shutdown(): Graceful shutdown, waits for tasks to complete
- shutdownNow(): Force shutdown, interrupts running tasks
0 Comments