Mẫu luồng nâng cao

Tối ưu hóa mã trong Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Nền tảng thread pool

Tạo luồng rất tốn kém!

$$

Thread pool:

  • Tái sử dụng luồng có sẵn
  • Kiểm soát số luồng đồng thời
  • Quản lý qua giao diện ExecutorService
Tối ưu hóa mã trong Java

Tạo thread pool

// Fixed thread pool with 4 threads
ExecutorService fixedPool = Executors.newFixedThreadPool(4);


// Cached thread pool that grows as needed ExecutorService cachedPool = Executors.newCachedThreadPool();
// Single-threaded executor ExecutorService singleExecutor = Executors.newSingleThreadExecutor();
Tối ưu hóa mã trong Java

Gửi tác vụ

ExecutorService executor = Executors.newFixedThreadPool(4);

// Submit a task with no return value
executor.execute(() -> System.out.println("Simple task"));

// Submit a task with a return value (Callable)
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

// Get result from Future (blocks until complete)
int result = future.get();
Tối ưu hóa mã trong Java

Tắt executor

// Signal shutdown, but continue running existing tasks
executor.shutdown();


// Wait for termination (with timeout) boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS);
// Force immediate shutdown, canceling running tasks executor.shutdownNow();
Tối ưu hóa mã trong Java

Completable future

  • CompletableFuture
  • Thuộc API đồng thời của Java từ Java 8
  • Cách hiện đại để lập trình bất đồng bộ
  • Có thể hoàn thành thủ công hoặc qua Function
  • Cho phép xâu chuỗi thao tác bằng callback
  • Hoạt động có hoặc không có thread pool tường minh
Tối ưu hóa mã trong Java

Tạo completable future

// Run async with default executor
CompletableFuture<Void> runAsync = 
    CompletableFuture.runAsync(() -> performTask());

// Supply async with custom executor ExecutorService executor = Executors.newCachedThreadPool(); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> fetchData(), executor);
Tối ưu hóa mã trong Java

Xâu chuỗi thao tác

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> fetchUserData(userId))
    .thenApply(data -> extractUsername(data))
    .exceptionally(ex -> "Unknown user");

// Access to result when ready
future.thenAccept(result -> System.out.println(result));
Tối ưu hóa mã trong Java

Ayo berlatih!

Tối ưu hóa mã trong Java

Preparing Video For Download...