Programming Search⌘K

Patterncore

Active Object

Also called active object, concurrent object, actor object.

Active Object gives an object its own thread. A proxy turns each method call into a request on a queue and returns a future, and a scheduler runs the requests on the object one at a time.

Family
concurrency
Intent
Decouple method execution from method invocation, to enhance concurrency and simplify synchronized access to an object that resides in its own thread of control.
Also called
Concurrent Object, Actor

Intent

The Active Object design pattern decouples method execution from method invocation to enhance concurrency and simplify synchronized access to an object that resides in its own thread of control.1 It is also known as Concurrent Object and Actor.1

Problem

Many applications benefit from using concurrent objects to improve their QoS, for example by allowing an application to handle multiple client requests in parallel.1 The paper's example is a communication Gateway that routes messages from supplier processes to consumer processes over TCP.1 TCP uses flow control to ensure that fast suppliers or Gateways do not produce data more rapidly than slow consumers or congested networks can buffer and process the data.1 The connections that are flow controlled must block without impeding the progress of threads whose TCP connections are not flow controlled.1 A passive object runs its methods in the thread of the client that calls it, so a slow call blocks that client.

Solution

An active object consists of these components:1

  • A Proxy represents the interface of the object and runs in the client thread.1
  • A Servant provides the object's implementation and runs in a different thread.1
  • At run time, the Proxy transforms the client's method invocation into a Method Request, which is stored in an Activation Queue by a Scheduler.1
  • The Scheduler runs continuously in the same thread as the servant. It dequeues Method Requests from the Activation Queue when they become runnable and dispatches them on the Servant.1
  • Clients can obtain the results of a method's execution via the Future returned by the Proxy.1
client thread                     scheduler thread
proxy.deposit(1)
  -> MethodRequest(deposit, 1) -> activation queue
  <- future                       scheduler: dequeue
future.result() ................> servant.deposit(1)
                                  future.set(result)

The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for handling requests.2 The client thread appears to invoke an ordinary method.1

Example

The example files show an account as an active object in each language. The servant keeps a total and has no lock, because only the scheduler thread calls it. Four client threads each call deposit(1) 250 times, and each call returns a future at once. The demo holds the scheduler at a gate until the clients end, so no request has run when the program counts the finished futures. Then it opens the gate and waits for the future of balance. The JavaScript and TypeScript versions put the servant in a worker thread. The program prints:

deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
PythonGitHub
import queue
import threading
from concurrent.futures import Future


class AccountServant:
    """The implementation. Only the scheduler thread calls it, so it has no lock."""

    def __init__(self):
        self.total = 0

    def deposit(self, amount):
        self.total += amount
        return self.total

    def balance(self):
        return self.total


class Scheduler(threading.Thread):
    def __init__(self, servant):
        super().__init__(daemon=True)
        self.servant = servant
        self.activation_queue = queue.Queue()
        self.gate = threading.Event()  # lets the demo hold the scheduler

    def run(self):
        self.gate.wait()
        while True:
            name, args, future = self.activation_queue.get()
            if name is None:
                return
            future.set_result(getattr(self.servant, name)(*args))


class AccountProxy:
    """The interface. A call becomes a method request and returns a future."""

    def __init__(self):
        self.scheduler = Scheduler(AccountServant())
        self.scheduler.start()

    def _request(self, name, *args):
        future = Future()
        self.scheduler.activation_queue.put((name, args, future))
        return future

    def deposit(self, amount):
        return self._request("deposit", amount)

    def balance(self):
        return self._request("balance")

    def stop(self):
        self.scheduler.activation_queue.put((None, (), None))
        self.scheduler.join()


account = AccountProxy()
per_client = [[] for _ in range(4)]


def client(mine):
    for _ in range(250):
        mine.append(account.deposit(1))  # each call returns at once


clients = [threading.Thread(target=client, args=(mine,)) for mine in per_client]
for t in clients:
    t.start()
for t in clients:
    t.join()
futures = [f for mine in per_client for f in mine]
print("deposits queued:", len(futures))
print("deposits done before the scheduler starts:", sum(f.done() for f in futures))
account.scheduler.gate.set()
print("balance after 1000 deposits:", account.balance().result())
account.stop()
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: library. queue.Queue is the activation queue and concurrent.futures.Future is the future. The proxy, scheduler and servant are plain classes.
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

// The servant: only the scheduler thread calls it, so it has no lock.
struct AccountServant {
    int total = 0;
    int deposit(int amount) { return total += amount; }
    int balance() const { return total; }
};

// The proxy: each method makes a request and returns a future at once.
class AccountProxy {
public:
    AccountProxy() : scheduler_([this] { schedule(); }) {}

    std::future<int> deposit(int amount) {
        return send([amount](AccountServant& s) { return s.deposit(amount); });
    }
    std::future<int> balance() {
        return send([](AccountServant& s) { return s.balance(); });
    }
    void open_gate() {  // lets the demo hold the scheduler
        std::lock_guard<std::mutex> guard(mutex_);
        open_ = true;
        ready_.notify_one();
    }
    ~AccountProxy() {
        {
            std::lock_guard<std::mutex> guard(mutex_);
            stop_ = true;
            ready_.notify_one();
        }
        scheduler_.join();
    }

private:
    using Request = std::function<void(AccountServant&)>;

    std::future<int> send(std::function<int(AccountServant&)> call) {
        auto future = std::make_shared<std::promise<int>>();
        auto result = future->get_future();
        std::lock_guard<std::mutex> guard(mutex_);
        activation_queue_.push([call, future](AccountServant& s) { future->set_value(call(s)); });
        ready_.notify_one();
        return result;
    }

    void schedule() {
        for (;;) {
            std::unique_lock<std::mutex> lock(mutex_);
            ready_.wait(lock, [this] { return stop_ || (open_ && !activation_queue_.empty()); });
            if (activation_queue_.empty() || !open_) return;
            Request request = std::move(activation_queue_.front());
            activation_queue_.pop();
            lock.unlock();
            request(servant_);
        }
    }

    AccountServant servant_;
    std::queue<Request> activation_queue_;
    std::mutex mutex_;
    std::condition_variable ready_;
    bool open_ = false, stop_ = false;
    std::thread scheduler_;
};

int main() {
    AccountProxy account;
    std::vector<std::vector<std::future<int>>> per_client(4);
    std::vector<std::thread> clients;
    for (auto& mine : per_client)
        clients.emplace_back([&account, &mine] {
            for (int i = 0; i < 250; ++i) mine.push_back(account.deposit(1));  // returns at once
        });
    for (auto& t : clients) t.join();
    int queued = 0, done = 0;
    for (auto& mine : per_client)
        for (auto& f : mine) {
            ++queued;
            if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) ++done;
        }
    std::cout << "deposits queued: " << queued << "\n";
    std::cout << "deposits done before the scheduler starts: " << done << "\n";
    account.open_gate();
    std::cout << "balance after 1000 deposits: " << account.balance().get() << "\n";
}
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: idiom. The standard library gives std::promise and std::future, and the example builds the activation queue from a mutex, a condition variable and std::queue.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    // The servant: only the scheduler thread calls it, so it has no lock.
    static class AccountServant {
        private int total = 0;
        int deposit(int amount) { total += amount; return total; }
        int balance() { return total; }
    }

    // The proxy: each method makes a request and returns a future at once.
    static class AccountProxy {
        private final AccountServant servant = new AccountServant();
        private final ExecutorService scheduler = Executors.newSingleThreadExecutor();
        final CountDownLatch gate = new CountDownLatch(1); // lets the demo hold the scheduler

        AccountProxy() {
            scheduler.execute(() -> {
                try {
                    gate.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        CompletableFuture<Integer> deposit(int amount) {
            return CompletableFuture.supplyAsync(() -> servant.deposit(amount), scheduler);
        }

        CompletableFuture<Integer> balance() {
            return CompletableFuture.supplyAsync(servant::balance, scheduler);
        }

        void stop() { scheduler.shutdown(); }
    }

    public static void main(String[] args) throws Exception {
        AccountProxy account = new AccountProxy();
        List<List<CompletableFuture<Integer>>> perClient = new ArrayList<>();
        List<Thread> clients = new ArrayList<>();
        for (int c = 0; c < 4; c++) {
            List<CompletableFuture<Integer>> mine = new ArrayList<>();
            perClient.add(mine);
            Thread t = new Thread(() -> {
                for (int i = 0; i < 250; i++) mine.add(account.deposit(1)); // returns at once
            });
            clients.add(t);
            t.start();
        }
        for (Thread t : clients) t.join();
        int queued = 0, done = 0;
        for (List<CompletableFuture<Integer>> mine : perClient) {
            for (CompletableFuture<Integer> f : mine) {
                queued++;
                if (f.isDone()) done++;
            }
        }
        System.out.println("deposits queued: " + queued);
        System.out.println("deposits done before the scheduler starts: " + done);
        account.gate.countDown();
        System.out.println("balance after 1000 deposits: " + account.balance().get());
        account.stop();
    }
}
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: stdlib. A single-thread ExecutorService is the scheduler with its queue, and CompletableFuture is the future.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

// The servant: only the scheduler thread calls it, so it has no lock.
class AccountServant
{
    private int total;
    public int Deposit(int amount) => total += amount;
    public int Balance() => total;
}

// The proxy: each method makes a request and returns a future at once.
class AccountProxy
{
    private readonly AccountServant servant = new();
    private readonly BlockingCollection<Action> activationQueue = new();
    private readonly Thread scheduler;
    public readonly ManualResetEventSlim Gate = new(false); // lets the demo hold the scheduler

    public AccountProxy()
    {
        scheduler = new Thread(() =>
        {
            Gate.Wait();
            foreach (var request in activationQueue.GetConsumingEnumerable()) request();
        });
        scheduler.Start();
    }

    private Task<int> Send(Func<AccountServant, int> call)
    {
        var future = new TaskCompletionSource<int>();
        activationQueue.Add(() => future.SetResult(call(servant)));
        return future.Task;
    }

    public Task<int> Deposit(int amount) => Send(s => s.Deposit(amount));
    public Task<int> Balance() => Send(s => s.Balance());

    public void Stop()
    {
        activationQueue.CompleteAdding();
        scheduler.Join();
    }
}

static class Program
{
    static void Main()
    {
        var account = new AccountProxy();
        var perClient = Enumerable.Range(0, 4).Select(_ => new List<Task<int>>()).ToList();
        var clients = perClient.Select(mine => new Thread(() =>
        {
            for (int i = 0; i < 250; i++) mine.Add(account.Deposit(1)); // returns at once
        })).ToList();
        clients.ForEach(t => t.Start());
        clients.ForEach(t => t.Join());
        var futures = perClient.SelectMany(mine => mine).ToList();
        Console.WriteLine("deposits queued: " + futures.Count);
        Console.WriteLine("deposits done before the scheduler starts: " + futures.Count(f => f.IsCompleted));
        account.Gate.Set();
        Console.WriteLine("balance after 1000 deposits: " + account.Balance().Result);
        account.Stop();
    }
}
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: library. BlockingCollection is the activation queue and TaskCompletionSource makes the future. The scheduler is a plain thread.
JavaScriptGitHub
const { Worker } = require("node:worker_threads");

// The servant and the scheduler run in a worker thread. The worker keeps
// the activation queue and starts to run it when it gets "start".
const schedulerCode = `
const { parentPort } = require("node:worker_threads");
const servant = { total: 0 };
const methods = {
  deposit: (amount) => (servant.total += amount),
  balance: () => servant.total,
};
const activationQueue = [];
let started = false;
const run = () => {
  while (activationQueue.length > 0) {
    const { id, name, args } = activationQueue.shift();
    parentPort.postMessage({ id, result: methods[name](...args) });
  }
};
parentPort.on("message", (message) => {
  if (message === "start") started = true;
  else activationQueue.push(message);
  if (started) run();
});
`;

// The proxy: each method makes a request and returns a future at once.
class AccountProxy {
  worker = new Worker(schedulerCode, { eval: true });
  pending = new Map();
  nextId = 0;

  constructor() {
    this.worker.on("message", ({ id, result }) => {
      this.pending.get(id)(result);
      this.pending.delete(id);
    });
  }

  send(name, ...args) {
    const id = this.nextId++;
    const future = { promise: Promise.resolve(0), done: false };
    future.promise = new Promise((resolve) => {
      this.pending.set(id, (result) => {
        future.done = true;
        resolve(result);
      });
    });
    this.worker.postMessage({ id, name, args });
    return future;
  }

  deposit(amount) {
    return this.send("deposit", amount);
  }

  balance() {
    return this.send("balance");
  }

  start() {
    this.worker.postMessage("start");
  }

  stop() {
    return this.worker.terminate();
  }
}

async function main() {
  const account = new AccountProxy();
  const client = () => Array.from({ length: 250 }, () => account.deposit(1));
  const futures = [client(), client(), client(), client()].flat();
  await new Promise((resolve) => setTimeout(resolve, 100)); // the worker gets the requests
  console.log("deposits queued:", futures.length);
  console.log("deposits done before the scheduler starts:", futures.filter((f) => f.done).length);
  account.start();
  console.log("balance after 1000 deposits:", await account.balance().promise);
  await account.stop();
}

main();
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: library. worker_threads gives the servant its own thread, and a promise is the future. The four clients are functions on the main thread, because the main thread is the only client thread.
TypeScriptGitHub
import { Worker } from "node:worker_threads";

// The servant and the scheduler run in a worker thread. The worker keeps
// the activation queue and starts to run it when it gets "start".
const schedulerCode = `
const { parentPort } = require("node:worker_threads");
const servant = { total: 0 };
const methods = {
  deposit: (amount) => (servant.total += amount),
  balance: () => servant.total,
};
const activationQueue = [];
let started = false;
const run = () => {
  while (activationQueue.length > 0) {
    const { id, name, args } = activationQueue.shift();
    parentPort.postMessage({ id, result: methods[name](...args) });
  }
};
parentPort.on("message", (message) => {
  if (message === "start") started = true;
  else activationQueue.push(message);
  if (started) run();
});
`;

type Future = { promise: Promise<number>; done: boolean };

// The proxy: each method makes a request and returns a future at once.
class AccountProxy {
  private worker = new Worker(schedulerCode, { eval: true });
  private pending = new Map<number, (result: number) => void>();
  private nextId = 0;

  constructor() {
    this.worker.on("message", ({ id, result }: { id: number; result: number }) => {
      this.pending.get(id)!(result);
      this.pending.delete(id);
    });
  }

  private send(name: string, ...args: number[]): Future {
    const id = this.nextId++;
    const future: Future = { promise: Promise.resolve(0), done: false };
    future.promise = new Promise<number>((resolve) => {
      this.pending.set(id, (result) => {
        future.done = true;
        resolve(result);
      });
    });
    this.worker.postMessage({ id, name, args });
    return future;
  }

  deposit(amount: number): Future {
    return this.send("deposit", amount);
  }

  balance(): Future {
    return this.send("balance");
  }

  start(): void {
    this.worker.postMessage("start");
  }

  stop(): Promise<number> {
    return this.worker.terminate();
  }
}

async function main(): Promise<void> {
  const account = new AccountProxy();
  const client = (): Future[] => Array.from({ length: 250 }, () => account.deposit(1));
  const futures = [client(), client(), client(), client()].flat();
  await new Promise((resolve) => setTimeout(resolve, 100)); // the worker gets the requests
  console.log("deposits queued:", futures.length);
  console.log("deposits done before the scheduler starts:", futures.filter((f) => f.done).length);
  account.start();
  console.log("balance after 1000 deposits:", await account.balance().promise);
  await account.stop();
}

main();
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: library. worker_threads gives the servant its own thread, and a promise is the future. The four clients are functions on the main thread, because the main thread is the only client thread.
package main

import (
	"fmt"
	"sync"
)

// The servant: only the scheduler goroutine touches it, so it has no lock.
type accountServant struct{ total int }

// A method request carries the call and the future for its result.
type request struct {
	call   func(*accountServant) int
	future chan int
}

// The proxy: each method makes a request and returns a future at once.
type AccountProxy struct {
	activation chan request
	gate       chan struct{} // lets the demo hold the scheduler
	done       chan struct{}
}

func NewAccountProxy() *AccountProxy {
	p := &AccountProxy{
		activation: make(chan request, 2000),
		gate:       make(chan struct{}),
		done:       make(chan struct{}),
	}
	go p.schedule(&accountServant{})
	return p
}

func (p *AccountProxy) schedule(s *accountServant) {
	<-p.gate
	for r := range p.activation {
		r.future <- r.call(s)
	}
	close(p.done)
}

func (p *AccountProxy) send(call func(*accountServant) int) chan int {
	future := make(chan int, 1)
	p.activation <- request{call, future}
	return future
}

func (p *AccountProxy) Deposit(amount int) chan int {
	return p.send(func(s *accountServant) int { s.total += amount; return s.total })
}

func (p *AccountProxy) Balance() chan int {
	return p.send(func(s *accountServant) int { return s.total })
}

func main() {
	account := NewAccountProxy()
	perClient := make([][]chan int, 4)
	var wg sync.WaitGroup
	for c := range perClient {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < 250; i++ {
				perClient[c] = append(perClient[c], account.Deposit(1)) // returns at once
			}
		}()
	}
	wg.Wait()
	queued, done := 0, 0
	for _, futures := range perClient {
		for _, f := range futures {
			queued++
			done += len(f)
		}
	}
	fmt.Println("deposits queued:", queued)
	fmt.Println("deposits done before the scheduler starts:", done)
	close(account.gate)
	fmt.Println("balance after 1000 deposits:", <-account.Balance())
	close(account.activation)
	<-account.done
}
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: idiom. A buffered channel is the activation queue, a goroutine is the scheduler, and a channel with room for one value is the future.
RustGitHub
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread::{self, JoinHandle};

// The servant: only the scheduler thread owns it, so it has no lock.
struct AccountServant {
    total: i32,
}

// A method request: a call to run on the servant.
type Request = Box<dyn FnOnce(&mut AccountServant) + Send>;

// The proxy: each method makes a request and returns a future at once.
struct AccountProxy {
    activation: Option<Sender<Request>>,
    gate: Sender<()>, // lets the demo hold the scheduler
    scheduler: Option<JoinHandle<()>>,
}

impl AccountProxy {
    fn new() -> AccountProxy {
        let (activation, queue) = channel::<Request>();
        let (gate, gate_rx) = channel::<()>();
        let scheduler = thread::spawn(move || {
            let mut servant = AccountServant { total: 0 };
            let _ = gate_rx.recv();
            for request in queue {
                request(&mut servant);
            }
        });
        AccountProxy { activation: Some(activation), gate, scheduler: Some(scheduler) }
    }

    fn send(&self, call: impl FnOnce(&mut AccountServant) -> i32 + Send + 'static) -> Receiver<i32> {
        let (future, result) = channel();
        let request: Request = Box::new(move |s| {
            let _ = future.send(call(s));
        });
        self.activation.as_ref().unwrap().send(request).unwrap();
        result
    }

    fn deposit(&self, amount: i32) -> Receiver<i32> {
        self.send(move |s| {
            s.total += amount;
            s.total
        })
    }

    fn balance(&self) -> Receiver<i32> {
        self.send(|s| s.total)
    }
}

impl Drop for AccountProxy {
    fn drop(&mut self) {
        self.activation.take(); // closing the queue ends the scheduler loop
        self.scheduler.take().unwrap().join().unwrap();
    }
}

fn main() {
    let account = AccountProxy::new();
    let per_client: Vec<Vec<Receiver<i32>>> = thread::scope(|s| {
        let handles: Vec<_> = (0..4)
            .map(|_| s.spawn(|| (0..250).map(|_| account.deposit(1)).collect::<Vec<_>>()))
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    });
    let futures: Vec<&Receiver<i32>> = per_client.iter().flatten().collect();
    let done = futures.iter().filter(|f| f.try_recv().is_ok()).count();
    println!("deposits queued: {}", futures.len());
    println!("deposits done before the scheduler starts: {done}");
    account.gate.send(()).unwrap();
    println!("balance after 1000 deposits: {}", account.balance().recv().unwrap());
}
Output
deposits queued: 1000
deposits done before the scheduler starts: 0
balance after 1000 deposits: 1000
  • Verdict: idiom. An mpsc channel of boxed closures is the activation queue, and a one-value channel is the future. The servant moves into the scheduler thread, so no other thread can reach it.

Consequences

Benefits:1

  • Enhance application concurrency and simplify synchronization complexity. Client threads and asynchronous method executions run simultaneously. The Scheduler evaluates synchronization constraints to guarantee serialized access to Servants.1
  • Transparently leverage available parallelism. If the platform supports multiple CPUs efficiently, multiple active objects can execute in parallel, subject to their synchronization constraints.1
  • Method execution order can differ from method invocation order. Methods invoked asynchronously are executed based on their synchronization constraints, which may differ from their invocation order.1

Liabilities:1

  • Performance overhead. Context switching, synchronization, and data movement overhead may occur when scheduling and executing method invocations. The pattern is most applicable on relatively coarse-grained objects.1
  • Complicated debugging. It may be difficult to debug programs containing active objects due to the concurrency and non-determinism of the Scheduler.1

A servant method must not wait for a future of its own active object. The request it waits for sits in the queue behind the running request, and only the same scheduler thread can run it. In this version, the wait has a timeout, so the program shows the failure instead of hanging:

This code runs but gives a wrong answer on purpose.

import queue
import threading
from concurrent.futures import Future, TimeoutError


class Scheduler(threading.Thread):
    def __init__(self):
        super().__init__(daemon=True)
        self.activation_queue = queue.Queue()

    def run(self):
        while True:
            call, future = self.activation_queue.get()
            future.set_result(call())


scheduler = Scheduler()
scheduler.start()


def send(call):
    future = Future()
    scheduler.activation_queue.put((call, future))
    return future


total = 0


def balance():
    return total


def report():
    # Runs in the scheduler thread, then waits for a request that
    # only the same scheduler thread can run.
    try:
        return send(balance).result(timeout=0.2)
    except TimeoutError:
        return "deadlock: the scheduler waits for itself"


print("report:", send(report).result())
Output
report: deadlock: the scheduler waits for itself

When not to use it

  • The object is very fine-grained. The performance overhead of active objects can be excessive then, compared with other concurrency patterns such as Monitors.1
  • Callers need each result at once and have nothing else to do. A future that the caller waits on at once only adds a thread switch to a plain locked call.
  • The servant's methods must call each other through the proxy and wait for the results. That makes the scheduler wait for itself, as the block above shows.
  • Integrated Scheduler. The roles of the Proxy and Servant are often integrated into the Scheduler component, though servants still execute in a different thread than the proxies.1
  • Message passing. A further refinement removes the Proxy and Servant altogether and uses direct message passing between the client thread and the Scheduler thread.1
  • Polymorphic futures. A Polymorphic Future result value provides write-once, read-many synchronization.1
  • Distributed Active Object. A distribution boundary exists between the Proxy and the Scheduler, rather than a threading boundary, and the client-side Proxy plays the role of a stub.1
  • Thread pool. A thread pool is a generalization of Active Object that supports multiple Servants per Active Object.1
  • Actors. The Active Object pattern has been used to implement Actors. Messages sent to an Actor are queued in the Actor's message queue.1
  • Monitor Object. Monitors are generally more efficient than Active Objects since they incur less context switching and data movement overhead, but it is harder to add a distribution boundary between client and server threads.1
  • Half-Sync/Half-Async. That pattern typically uses Active Object to implement the synchronous task layer and Reactor to implement the asynchronous task layer.1 POSA2 lists Active Object first among its concurrency patterns.3
  • Command Processor. Its intent is to separate the issuing of requests from their execution, and the command processor corresponds to the scheduler.1

In Python, a ThreadPoolExecutor with one worker gives the scheduler and the activation queue in one object. It uses a pool of at most max_workers threads to execute calls asynchronously, and submit returns a Future:4

from concurrent.futures import ThreadPoolExecutor


class AccountServant:
    def __init__(self):
        self.total = 0

    def deposit(self, amount):
        self.total += amount
        return self.total


servant = AccountServant()
# One worker thread: the executor is the scheduler and its activation queue.
with ThreadPoolExecutor(max_workers=1) as scheduler:
    futures = [scheduler.submit(servant.deposit, 1) for _ in range(1000)]
    print("last deposit result:", futures[-1].result())
    print("results in call order:", [f.result() for f in futures[:5]])
Output
last deposit result: 1000
results in call order: [1, 2, 3, 4, 5]

Known uses

  • CORBA ORBs. The pattern has been used to implement concurrent ORB middleware frameworks. The TAO ORB implements it for its default concurrency model: CORBA stubs are the Proxies, the ORB Core's Reactor is the Scheduler, and the socket queues are the Activation Queues.1
  • ACE. Reusable implementations of the Method Request, Activation Queue, and Future components are provided in the ACE framework.1
  • Siemens MedCom. The framework for electronic medical systems uses the pattern with the Command Processor pattern.1
  • Siemens Call Center management system. This system uses the thread pool variant.1
  • Clients. Client applications, such as windowing systems and network browsers, employ active objects to simplify concurrent, asynchronous network operations.1

References

  1. R. Greg Lavender and Douglas C. Schmidt, Active Object: An Object Behavioral Pattern for Concurrent Programming, Abstract; 1 Intent; 2 Also Known As; 5 Problem; 11 Variants; 12 Known Uses; 13 Consequences; 14 See Also
  2. Active object, Wikipedia, lead
  3. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 5 Concurrency Patterns
  4. concurrent.futures, Launching parallel tasks, Python documentation, ThreadPoolExecutor; Future Objects

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/749ESG/text.yaml