Patterncore
Monitor Object
Also called monitor object, monitor, thread-safe passive object.
Monitor Object makes an object safe for many threads. Each method holds the object's lock while it runs, and a method that cannot go on waits on a condition that releases the lock.
- Family
- concurrency
- Intent
- Synchronize method execution so that only one method runs within an object at a time, and let the methods of the object cooperatively schedule their execution sequences.
- Also called
- Thread-safe Passive Object
Intent
The Monitor Object pattern synchronizes method execution to ensure only one method runs within an object at a time. It also allows an object's methods to cooperatively schedule their execution sequences.1 It is also known as Thread-safe Passive Object.1
Problem
Many applications contain objects that are accessed concurrently by multiple client threads, so it is often necessary to synchronize and schedule access to these objects.1 The paper's example is the message queue of a consumer handler in a communication Gateway. Its put and get operations must let multiple threads insert and remove messages simultaneously without corrupting the queue's internal state.1 The paper states these requirements:1
- Synchronization boundaries should correspond to object methods.1
- Objects, not clients, should be responsible for their own method synchronization. Concurrent applications are harder to program if clients must explicitly acquire and release low-level synchronization mechanisms, such as semaphores, mutexes, or condition variables.1
The same queue must also block a get on an empty queue and a put on a full queue until another thread changes the queue.1
Solution
Define each object that client threads access concurrently as a monitor object. Clients access its services only through its synchronized methods, and only one synchronized method at a time can run within the object.1 The participants are:1
- The monitor object exports one or more methods to clients. Each method executes in the thread of the client that invokes it, because a monitor object does not have its own thread of control.1
- The synchronized methods implement the thread-safe services of the object.1
- The monitor lock serializes method invocations on a per-object basis. Each synchronized method acquires it when the method enters the object and releases it when the method exits.1
- The monitor conditions let synchronized methods in separate threads cooperatively schedule their execution sequences, by waiting for and notifying each other.1
When a synchronized method cannot make progress, it waits on a monitor condition. The monitor lock is released automatically and the client thread is suspended. When another method notifies the condition, the lock is reacquired before the thread reenters the object and resumes.1
producer thread consumer thread
put(m): get():
acquire monitor lock acquire monitor lock
while full: wait not_full while empty: wait not_empty
add m (wait releases the lock)
notify not_empty -----------> wakes, reacquires the lock
release monitor lock remove m, notify not_full
release monitor lock
A thread that wakes from a wait must check its condition again, because other threads can run between the notify and the wakeup.2 Python's documentation gives the same rule: wait() can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true.3
Example
The example files implement a bounded message queue with room for 2 messages as a monitor object. One lock guards the queue, and two conditions, not full and not empty, let put and get wait. Four producer threads put 250 messages each, and two consumer threads get 500 messages each. Every message is a different number from 0 to 999, so the sum shows that no message was lost or read twice. The JavaScript and TypeScript versions use async functions on one thread: each job runs to completion before any other job is processed,4 so the methods need no lock, and a waiting method awaits a promise. The program prints:
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
import threading
class MessageQueue:
"""A monitor object: one lock, two conditions on that lock."""
def __init__(self, capacity):
self.capacity = capacity
self.items = []
self.lock = threading.Lock()
self.not_full = threading.Condition(self.lock)
self.not_empty = threading.Condition(self.lock)
self.puts = 0
self.gets = 0
self.largest = 0
def put(self, message):
with self.lock:
while len(self.items) == self.capacity:
self.not_full.wait() # releases the lock while it waits
self.items.append(message)
self.puts += 1
self.largest = max(self.largest, len(self.items))
self.not_empty.notify()
def get(self):
with self.lock:
while not self.items:
self.not_empty.wait()
message = self.items.pop(0)
self.gets += 1
self.not_full.notify()
return message
q = MessageQueue(2)
got = [[], []]
def producer(p):
for i in range(250):
q.put(p * 250 + i)
def consumer(mine):
for _ in range(500):
mine.append(q.get())
threads = [threading.Thread(target=producer, args=(p,)) for p in range(4)]
threads += [threading.Thread(target=consumer, args=(mine,)) for mine in got]
for t in threads:
t.start()
for t in threads:
t.join()
print("messages put:", q.puts)
print("messages got:", q.gets)
print("sum of messages got:", sum(got[0]) + sum(got[1]))
print("queue never held more than 2:", q.largest <= 2)
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: stdlib.
threading.Conditiontakes an existing lock, so the two conditions share the monitor lock.
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
class MessageQueue {
public:
explicit MessageQueue(std::size_t capacity) : capacity_(capacity) {}
void put(int message) {
std::unique_lock<std::mutex> lock(mutex_);
// wait releases the lock, and the predicate is checked again on wakeup.
not_full_.wait(lock, [this] { return items_.size() < capacity_; });
items_.push_back(message);
++puts;
largest = std::max(largest, items_.size());
not_empty_.notify_one();
}
int get() {
std::unique_lock<std::mutex> lock(mutex_);
not_empty_.wait(lock, [this] { return !items_.empty(); });
int message = items_.front();
items_.pop_front();
++gets;
not_full_.notify_one();
return message;
}
int puts = 0;
int gets = 0;
std::size_t largest = 0;
private:
std::size_t capacity_;
std::deque<int> items_;
std::mutex mutex_;
std::condition_variable not_full_;
std::condition_variable not_empty_;
};
int main() {
MessageQueue q(2);
long sums[2] = {0, 0};
std::vector<std::thread> threads;
for (int p = 0; p < 4; ++p)
threads.emplace_back([&q, p] { for (int i = 0; i < 250; ++i) q.put(p * 250 + i); });
for (int c = 0; c < 2; ++c)
threads.emplace_back([&q, &sums, c] { for (int i = 0; i < 500; ++i) sums[c] += q.get(); });
for (auto& t : threads) t.join();
std::cout << "messages put: " << q.puts << "\n";
std::cout << "messages got: " << q.gets << "\n";
std::cout << "sum of messages got: " << sums[0] + sums[1] << "\n";
std::cout << "queue never held more than 2: " << (q.largest <= 2 ? "True" : "False") << "\n";
}
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: stdlib.
std::mutexis the monitor lock and twostd::condition_variableobjects are the monitor conditions. The class keeps the lock private, so clients cannot skip it.
import java.util.ArrayDeque;
public class Main {
// Every Java object is a monitor: synchronized methods take its lock,
// and wait and notifyAll use its single wait queue.
static class MessageQueue {
private final int capacity;
private final ArrayDeque<Integer> items = new ArrayDeque<>();
int puts = 0;
int gets = 0;
int largest = 0;
MessageQueue(int capacity) {
this.capacity = capacity;
}
synchronized void put(int message) throws InterruptedException {
while (items.size() == capacity) {
wait(); // releases the monitor lock while it waits
}
items.addLast(message);
puts++;
largest = Math.max(largest, items.size());
notifyAll(); // one wait queue holds both kinds of waiters
}
synchronized int get() throws InterruptedException {
while (items.isEmpty()) {
wait();
}
int message = items.removeFirst();
gets++;
notifyAll();
return message;
}
}
public static void main(String[] args) throws InterruptedException {
MessageQueue q = new MessageQueue(2);
long[] sums = new long[2];
Thread[] threads = new Thread[6];
for (int p = 0; p < 4; p++) {
final int base = p * 250;
threads[p] = new Thread(() -> {
try {
for (int i = 0; i < 250; i++) q.put(base + i);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
for (int c = 0; c < 2; c++) {
final int slot = c;
threads[4 + c] = new Thread(() -> {
try {
for (int i = 0; i < 500; i++) sums[slot] += q.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
synchronized (q) {
System.out.println("messages put: " + q.puts);
System.out.println("messages got: " + q.gets);
System.out.println("sum of messages got: " + (sums[0] + sums[1]));
System.out.println("queue never held more than 2: " + (q.largest <= 2 ? "True" : "False"));
}
}
}
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: native.
synchronized,waitandnotifyAllare part of the language and ofObject. The single wait queue holds producers and consumers, so the code callsnotifyAlland each thread checks its condition again.
using System;
using System.Collections.Generic;
using System.Threading;
class MessageQueue
{
private readonly object monitor = new object();
private readonly Queue<int> items = new Queue<int>();
private readonly int capacity;
public int Puts, Gets, Largest;
public MessageQueue(int capacity) => this.capacity = capacity;
public void Put(int message)
{
lock (monitor)
{
while (items.Count == capacity)
Monitor.Wait(monitor); // releases the lock while it waits
items.Enqueue(message);
Puts++;
Largest = Math.Max(Largest, items.Count);
Monitor.PulseAll(monitor);
}
}
public int Get()
{
lock (monitor)
{
while (items.Count == 0)
Monitor.Wait(monitor);
int message = items.Dequeue();
Gets++;
Monitor.PulseAll(monitor);
return message;
}
}
}
class Program
{
static void Main()
{
var q = new MessageQueue(2);
long[] sums = new long[2];
var threads = new List<Thread>();
for (int p = 0; p < 4; p++)
{
int start = p * 250;
threads.Add(new Thread(() => { for (int i = 0; i < 250; i++) q.Put(start + i); }));
}
for (int c = 0; c < 2; c++)
{
int slot = c;
threads.Add(new Thread(() => { for (int i = 0; i < 500; i++) sums[slot] += q.Get(); }));
}
threads.ForEach(t => t.Start());
threads.ForEach(t => t.Join());
Console.WriteLine("messages put: " + q.Puts);
Console.WriteLine("messages got: " + q.Gets);
Console.WriteLine("sum of messages got: " + (sums[0] + sums[1]));
Console.WriteLine("queue never held more than 2: " + (q.Largest <= 2 ? "True" : "False"));
}
}
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: stdlib. The
lockstatement callsMonitor.EnterandMonitor.Exit, andMonitor.WaitandMonitor.PulseAllgive one wait queue per lock object.
// One thread runs every job to completion, so the methods need no lock.
// A method that cannot go on awaits a promise, which plays the condition.
class Condition {
constructor() {
this.waiters = [];
}
wait() {
return new Promise((resolve) => this.waiters.push(resolve));
}
notify() {
const resolve = this.waiters.shift();
if (resolve) resolve();
}
}
class MessageQueue {
constructor(capacity) {
this.capacity = capacity;
this.items = [];
this.notFull = new Condition();
this.notEmpty = new Condition();
this.puts = 0;
this.gets = 0;
this.largest = 0;
}
async put(message) {
while (this.items.length === this.capacity) {
await this.notFull.wait();
}
this.items.push(message);
this.puts += 1;
this.largest = Math.max(this.largest, this.items.length);
this.notEmpty.notify();
}
async get() {
while (this.items.length === 0) {
await this.notEmpty.wait();
}
const message = this.items.shift();
this.gets += 1;
this.notFull.notify();
return message;
}
}
async function main() {
const q = new MessageQueue(2);
let sum = 0;
const producer = async (p) => {
for (let i = 0; i < 250; i++) await q.put(p * 250 + i);
};
const consumer = async () => {
for (let i = 0; i < 500; i++) {
const message = await q.get();
sum += message;
}
};
await Promise.all([0, 1, 2, 3].map(producer).concat([consumer(), consumer()]));
console.log("messages put:", q.puts);
console.log("messages got:", q.gets);
console.log("sum of messages got:", sum);
console.log("queue never held more than 2:", q.largest <= 2 ? "True" : "False");
}
main();
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: idiom. The language has no monitor construct here. Single-threaded jobs give the mutual exclusion, and the
Conditionclass is a list of promise resolvers.
// One thread runs every job to completion, so the methods need no lock.
// A method that cannot go on awaits a promise, which plays the condition.
class Condition {
private waiters: Array<() => void> = [];
wait(): Promise<void> {
return new Promise((resolve) => this.waiters.push(resolve));
}
notify(): void {
const resolve = this.waiters.shift();
if (resolve) resolve();
}
}
class MessageQueue {
capacity: number;
items: number[] = [];
notFull = new Condition();
notEmpty = new Condition();
puts = 0;
gets = 0;
largest = 0;
constructor(capacity: number) {
this.capacity = capacity;
}
async put(message: number): Promise<void> {
while (this.items.length === this.capacity) {
await this.notFull.wait();
}
this.items.push(message);
this.puts += 1;
this.largest = Math.max(this.largest, this.items.length);
this.notEmpty.notify();
}
async get(): Promise<number> {
while (this.items.length === 0) {
await this.notEmpty.wait();
}
const message = this.items.shift()!;
this.gets += 1;
this.notFull.notify();
return message;
}
}
async function main(): Promise<void> {
const q = new MessageQueue(2);
let sum = 0;
const producer = async (p: number) => {
for (let i = 0; i < 250; i++) await q.put(p * 250 + i);
};
const consumer = async () => {
for (let i = 0; i < 500; i++) {
const message = await q.get();
sum += message;
}
};
await Promise.all([0, 1, 2, 3].map(producer).concat([consumer(), consumer()]));
console.log("messages put:", q.puts);
console.log("messages got:", q.gets);
console.log("sum of messages got:", sum);
console.log("queue never held more than 2:", q.largest <= 2 ? "True" : "False");
}
main();
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: idiom. The language has no monitor construct here. Single-threaded jobs give the mutual exclusion, and the typed
Conditionclass is a list of promise resolvers.
package main
import (
"fmt"
"sync"
)
// MessageQueue is a monitor object: one mutex and two sync.Cond values on it.
type MessageQueue struct {
mu sync.Mutex
notFull *sync.Cond
notEmpty *sync.Cond
items []int
capacity int
puts int
gets int
largest int
}
func NewMessageQueue(capacity int) *MessageQueue {
q := &MessageQueue{capacity: capacity}
q.notFull = sync.NewCond(&q.mu)
q.notEmpty = sync.NewCond(&q.mu)
return q
}
func (q *MessageQueue) Put(message int) {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == q.capacity {
q.notFull.Wait() // unlocks q.mu while it waits
}
q.items = append(q.items, message)
q.puts++
q.largest = max(q.largest, len(q.items))
q.notEmpty.Signal()
}
func (q *MessageQueue) Get() int {
q.mu.Lock()
defer q.mu.Unlock()
for len(q.items) == 0 {
q.notEmpty.Wait()
}
message := q.items[0]
q.items = q.items[1:]
q.gets++
q.notFull.Signal()
return message
}
func main() {
q := NewMessageQueue(2)
var sums [2]int
var wg sync.WaitGroup
for p := 0; p < 4; p++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 250; i++ {
q.Put(p*250 + i)
}
}()
}
for c := 0; c < 2; c++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
sums[c] += q.Get()
}
}()
}
wg.Wait()
fmt.Println("messages put:", q.puts)
fmt.Println("messages got:", q.gets)
fmt.Println("sum of messages got:", sums[0]+sums[1])
verdict := "False"
if q.largest <= 2 {
verdict = "True"
}
fmt.Println("queue never held more than 2:", verdict)
}
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: stdlib.
sync.Condtakes theLockerthat must be held when the code callsWait, so both conditions shareq.mu.
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
struct State {
items: VecDeque<u64>,
puts: u64,
gets: u64,
largest: usize,
}
// The Mutex owns the state, so no method can touch it without the lock.
struct MessageQueue {
state: Mutex<State>,
not_full: Condvar,
not_empty: Condvar,
capacity: usize,
}
impl MessageQueue {
fn put(&self, message: u64) {
let mut s = self.state.lock().unwrap();
// wait_while releases the lock while the condition holds.
s = self.not_full.wait_while(s, |s| s.items.len() == self.capacity).unwrap();
s.items.push_back(message);
s.puts += 1;
s.largest = s.largest.max(s.items.len());
self.not_empty.notify_one();
}
fn get(&self) -> u64 {
let mut s = self.state.lock().unwrap();
s = self.not_empty.wait_while(s, |s| s.items.is_empty()).unwrap();
let message = s.items.pop_front().unwrap();
s.gets += 1;
self.not_full.notify_one();
message
}
}
fn main() {
let q = Arc::new(MessageQueue {
state: Mutex::new(State { items: VecDeque::new(), puts: 0, gets: 0, largest: 0 }),
not_full: Condvar::new(),
not_empty: Condvar::new(),
capacity: 2,
});
let mut producers = Vec::new();
for p in 0..4u64 {
let q = Arc::clone(&q);
producers.push(thread::spawn(move || {
for i in 0..250 {
q.put(p * 250 + i);
}
}));
}
let consumers: Vec<_> = (0..2)
.map(|_| {
let q = Arc::clone(&q);
thread::spawn(move || (0..500).map(|_| q.get()).sum::<u64>())
})
.collect();
for t in producers {
t.join().unwrap();
}
let sum: u64 = consumers.into_iter().map(|t| t.join().unwrap()).sum();
let s = q.state.lock().unwrap();
println!("messages put: {}", s.puts);
println!("messages got: {}", s.gets);
println!("sum of messages got: {}", sum);
println!("queue never held more than 2: {}", if s.largest <= 2 { "True" } else { "False" });
}
messages put: 1000
messages got: 1000
sum of messages got: 499500
queue never held more than 2: True
- Verdict: stdlib.
MutexandCondvarare instd::sync. TheMutexowns the state, so the compiler rejects access to the items without the lock.
Consequences
Benefits:1
- Simplify synchronization of methods invoked concurrently on an object. Clients need not be concerned with concurrency control when they call a monitor object. If a language does not support monitor objects, idioms like Scoped Locking can automate the acquisition and release of monitor locks.1
- Synchronized methods can cooperatively schedule their order of execution. Methods can suspend themselves and wait to be notified when arbitrarily complex conditions occur, without inefficient polling.1
Liabilities:1
- Tight coupling between object functionality and synchronization mechanisms. A monitor object's synchronization and scheduling logic is often closely coupled with its methods' functionality. This makes monitor objects more efficient than active objects, but it may be hard to change their synchronization policies without changing the method implementations.1
- Nested monitor lockout. This problem can occur when a monitor object is nested within another monitor object. In the paper's Java example, a thread waits in the inner monitor and keeps the lock of the outer monitor, so no other thread can enter the outer monitor to make the condition true, and the first thread blocks forever.1
The block below shows nested monitor lockout. Outer.process holds the outer lock and waits on the inner condition. Outer.set must take the outer lock first, so it cannot run until the wait times out:
This code runs but gives a wrong answer on purpose.
import threading
class Inner:
def __init__(self):
self.cv = threading.Condition()
self.cond = False
def await_condition(self):
with self.cv:
# The wait releases the inner lock only. The timeout keeps the demo from hanging.
return self.cv.wait_for(lambda: self.cond, timeout=0.3)
def notify_condition(self, value):
with self.cv:
self.cond = value
self.cv.notify_all()
class Outer:
def __init__(self):
self.lock = threading.Lock()
self.inner = Inner()
self.entered = threading.Event()
self.order = []
def process(self):
with self.lock:
self.entered.set()
result = self.inner.await_condition()
self.order.append("process gave up")
return result
def set(self, value):
with self.lock:
self.order.append("set ran")
self.inner.notify_condition(value)
outer = Outer()
results = []
t1 = threading.Thread(target=lambda: results.append(outer.process()))
t1.start()
outer.entered.wait()
t2 = threading.Thread(target=outer.set, args=(True,))
t2.start()
t1.join()
t2.join()
print("process saw the condition:", results[0])
print("order:", outer.order)
process saw the condition: False
order: ['process gave up', 'set ran']
When not to use it
- The callers must not block in the object at all. Each synchronized method runs in the client thread,1 so a long wait in the method stops the client. Active Object runs the methods in a different thread than the clients.1
- The synchronization policy must change often. The policy is coupled with the methods, so a change can mean a change to each method.1
- Methods of one monitor must wait on a condition of another monitor. That is the nested monitor lockout that the block above shows.1
Variants and related patterns
- Timed synchronized method invocations. Clients can bound the amount of time they are willing to wait for a synchronized method to enter its monitor object's critical section.1
- Strategized locking. The Strategized Locking pattern can make a monitor object more flexible and reusable, for example by a template parameter that selects the lock and condition types of a Message Queue.1 Then the Thread-safe Interface idiom keeps intra-object calls from self-deadlock.1
- Active Object. Both patterns can synchronize and schedule methods invoked concurrently on an object. An active object executes its methods in a different thread than its clients, whereas a monitor object executes its methods in its client threads. Active objects can do more sophisticated, albeit more expensive, scheduling.1 POSA2 lists Monitor Object among its 17 patterns, next to Active Object.5
Python's queue.Queue is a monitor object with timed methods. Its source creates one lock, self.mutex, and the conditions not_empty and not_full on that lock.6 With a timeout, get blocks at most that many seconds and then raises the Empty exception, and put raises Full:6
import queue
q = queue.Queue(maxsize=1)
try:
q.get(timeout=0.1)
except queue.Empty:
print("get on an empty queue: timed out")
q.put("m1")
try:
q.put("m2", timeout=0.1)
except queue.Full:
print("put on a full queue: timed out")
get on an empty queue: timed out
put on a full queue: timed out
Known uses
- Dijkstra and Hoare monitors. Dijkstra and Hoare defined programming language features called monitors. A monitor contains a lock that allows only one function at a time to be active, and functions can block on a condition variable.1 Brinch Hansen created the first implementation of monitors, in Concurrent Pascal.2
- Java objects. Each Java object is implicitly a monitor that contains a monitor lock and a single monitor condition. Threads coordinate via explicit wait, notify, and notifyAll operations.1 Methods that need mutual exclusion are marked with the synchronized keyword.2
- ACE Gateway. The Message Queues used by Consumer Handlers in the Gateway are reusable ACE components implemented as monitor objects.1
- Languages. Languages that support monitors include C#, Go, Java, Mesa, Modula-3, Ruby, and Python through its
threading.Conditionobject.2
References
- Douglas C. Schmidt, Monitor Object: An Object Behavioral Pattern for Concurrent Programming, 1 Intent; 2 Also Known As; 5 Problem; 6 Solution; 7 Structure; 11 Variants; 12 Known Uses; 13 Consequences; 14 See Also
- Monitor (synchronization), Wikipedia, lead; Implicit condition variable monitors; History
- threading, Thread-based parallelism, Python documentation, Condition objects
- JavaScript execution model, MDN Web Docs, Run-to-completion
- Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Overview, the 17 patterns
- CPython source, Lib/queue.py, class Queue, __init__, put, get
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EAEHE8 Edit this page History Report an error Markdown