問題背景
多個 thread 同時呼叫同一個物件的 method,需要鎖機制保護共享狀態——加了鎖就有 deadlock 風險、lock contention,加了 lock 又讓 client 等待。
Active Object 的解法:物件有自己的 thread(activation thread)和 message queue(activation list)。外部呼叫 method 不是直接執行,而是把呼叫封裝成 message 放進 queue,物件自己的 thread 從 queue 取出來依序處理。
結構
Client → [proxy.doWork()] → ActivationList (Queue)
↓
Activation Thread(物件的私有 thread)
↓
real Object.doWork()
↓
Future(呼叫者可以等待結果)
概念實作(Java)
import java.util.concurrent.*;
class ActiveAccount {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private int balance;
public Future<Integer> getBalance() {
return executor.submit(() -> balance);
}
public Future<Void> deposit(int amount) {
return executor.submit(() -> {
balance += amount;
return null;
});
}
public Future<Boolean> withdraw(int amount) {
return executor.submit(() -> {
if (balance >= amount) {
balance -= amount;
return true;
}
return false;
});
}
}
// 使用
ActiveAccount account = new ActiveAccount();
account.deposit(100).get(); // 等待完成
Future<Boolean> result = account.withdraw(50); // 非同步
// 做其他事...
boolean success = result.get(); // 需要時再等結果和 Actor Model 的關係
Active Object 是 Actor Model 的前身(Hewitt 1973)。Erlang 的 process、Akka 的 Actor、Go 的 goroutine + channel——都是 Active Object 思想的不同實現:
- Actor 有自己的 mailbox(= Active Object 的 activation queue)
- Actor 透過 message 通信(= Active Object 把 method call 轉成 message)
- Actor 的狀態只有自己能存取(= 不需要鎖)
適用場景
- 需要 thread-safe 的有狀態物件(不想用 lock)
- 需要 async method call 和 future/promise 語意
- 狀態機的實作(state 只在 activation thread 裡修改)
現代語言的 async/await 和 event loop(Node.js、Python asyncio)是 Active Object 概念的語言層抽象——event loop 就是 activation queue,async function 就是 message。