Lamport's bakery algorithm

Lamport's bakery algorithm is a computer algorithm devised by computer scientist Leslie Lamport, as part of his long study of the formal correctness of concurrent systems, which is intended to improve the safety in the usage of shared resources among multiple threads by means of mutual exclusion.

In computer science, it is common for multiple threads to simultaneously access the same resources.

Due to the limitations of computer architecture, some parts of Lamport's analogy need slight modification.

It is possible that more than one thread will get the same number n when they request it; this cannot be avoided (without first solving the mutual exclusion problem, which is the goal of the algorithm).

The critical section is that part of code that requires exclusive access to resources and may only be executed by one thread at a time.

This part is analogous to actions that occur after shopping, such as putting change back into the wallet.

It is remarkable that this algorithm is not built on top of some lower level "atomic" operation, e.g. compare-and-swap.

Therefore, this algorithm can be used to implement mutual exclusion on memory that lacks synchronisation primitives, e.g., a simple SCSI disk shared between two computers.

Therefore, correct implementation of the algorithm typically requires inserting fences to inhibit reordering.

We use the AtomicIntegerArray class not for its built in atomic operations but because its get and set methods work like volatile reads and writes.