Producer-consumer
medium 50 minA bounded buffer between those who make work and those who do it.
Watch lesson4:26
Where it shows up
The same pattern appears across everyday software.
Java BlockingQueue
The interface is designed mainly for producer-consumer queues. `LinkedBlockingQueue` without a number has a capacity of Integer.MAX_VALUE, so in practice no limit. The documentation names poison objects as a common way to end.
Linux pipes
`ls | sort` connects two processes by a buffer in the kernel. By default it is 16 pages, 65,536 bytes with 4 KB pages. A write to a full pipe and a read from an empty pipe block.
Python logging
`QueueHandler` puts log records on a queue, `QueueListener` takes them in another thread and gives them to slow handlers. The request does not wait for the disk or the network.
Log4j 2 async loggers
Application threads write into an LMAX Disruptor, a lock-free library for passing data between threads, and a background thread writes to the appenders. A policy decides what happens when it is full.
Kafka producer client
`send` adds records to memory limited by `buffer.memory`. A background thread sends them in batches. When the memory is used up, `send` blocks up to `max.block.ms` and then throws.
RabbitMQ prefetch
A consumer can limit how many unacknowledged messages it holds. With no acknowledgement the broker sends no more: backpressure between machines.
Node.js streams
`write` returns false when the buffered amount has reached the `highWaterMark`. The producer should stop until the `drain` event: the same pattern with events in place of sleeping.
.NET channels
`Channel.CreateBounded` asks for a capacity and offers four modes for a full channel: wait, drop newest, drop oldest, drop write.
Amazon SQS
A received message becomes invisible for the visibility timeout and returns if it is not deleted in time. This is the lease of the FAANG page.
Print spooling, web servers, video players
Programs hand in documents and one thread feeds the printer. A web server queues accepted requests for its workers. A player holds decoded frames between decoder and screen.