Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง CompletableFuture และ Future ใน Java 9

CompletableFuture<T> class implements Future<T> interface ใน Java CompletableFuture ใช้เป็น Future ที่สามารถ complete ได้อย่างชัดเจน (explicitly completed)

Future interface ไม่ได้ให้ฟีเจอร์มากนัก ต้องใช้เมธอด get() เพื่อดึงผลลัพธ์ของ asynchronous computation ซึ่งเป็น blocking call จึงไม่สามารถรัน multiple dependent tasks แบบ non-blocking ได้ ในขณะที่ CompletableFuture class ให้ฟังก์ชันสำหรับ chain multiple dependent tasks ที่รัน asynchronously สามารถสร้าง chain ของ tasks โดย task ถัดไปจะถูก trigger เมื่อผลลัพธ์ของ task ปัจจุบันพร้อมแล้ว

Syntax

public class CompletableFuture<T> extends Object implements Future<T>, CompletionStage<T>

ตัวอย่างโค้ด

import java.util.function.Supplier;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureTest {
    public static void main(String args[]) throws ExecutionException, InterruptedException {
        Calculator calc = new Calculator(4, 7);
        
        // สร้าง CompletableFuture จาก Supplier
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(calc);
        
        // Chain task ถัดไปด้วย thenAccept (non-blocking)
        future.thenAccept(result -> {
            System.out.println("Result: " + result);
        });
        
        System.out.println("CompletableFutureTest End....");
        Thread.sleep(10000); // รอให้ async task เสร็จ
    }
}

// Calculator class implements Supplier
class Calculator implements Supplier<Integer> {
    private int x, y;
    
    public Calculator(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    @Override
    public Integer get() {
        try {
            Thread.sleep(3000); // จำลองงานที่ใช้เวลา
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        return x + y;
    }
}

ผลลัพธ์

CompletableFutureTest End....
Result: 11

ความแตกต่างหลัก

คุณสมบัติ Future CompletableFuture
Blocking get() ใช่ (block จนกว่าจะเสร็จ) ไม่บังคับ (มี non-blocking methods)
Chaining tasks ไม่รองรับ รองรับ (thenApply, thenAccept, thenCompose)
Exception handling ยาก ง่าย (exceptionally, handle)
Combining futures ไม่รองรับ รองรับ (thenCombine, allOf, anyOf)
Manual completion ไม่ได้ ได้ (complete, completeExceptionally)

เมธอดสำคัญของ CompletableFuture

  • supplyAsync() - รัน Supplier แบบ async
  • thenApply() - แปลงผลลัพธ์
  • thenAccept() - ใช้ผลลัพธ์ (ไม่คืนค่า)
  • thenRun() - รัน action หลังเสร็จ (ไม่ใช้ผลลัพธ์)
  • thenCompose() - chain CompletableFuture อีกตัว
  • exceptionally() - จัดการ exception
  • allOf()/anyOf() - รอ multiple futures