A Java 21 simulation of a shared print service: P client threads submit print jobs and C printer threads print them, all through one bounded FIFO queue of capacity K. The queue is synchronized with nothing but java.util.concurrent.Semaphore, and every run checks that every submitted job was printed exactly once.
This is a CMP3001 project. The assignment asked us to build a Java simulation of a shared print service. Several client threads produce print jobs, while several printer threads consume them. The queue has a fixed capacity, so clients must wait when it is full and printers must wait when it is empty. Use semaphores to coordinate access and demonstrate that every submitted job is processed exactly once.
This project applies process synchronization concepts using threads that share memory within one Java process.
- P clients each make J jobs (
C2-J5= client 2, job 5). Each job takes a random production delay, and then the clientputs it into the queue. A client blocks while the queue is full. - C printers
takejobs and "print" each one for a random delay. A printer blocks while the queue is empty. Printing happens outside the queue, so several printers really do print at the same time. - When all clients are done, the driver puts one stop job per printer (
STOP-1…STOP-C) and waits for the printers to exit. - At the end it verifies the run and prints a summary: jobs submitted and printed, max queue size vs K, max printers printing at once, jobs per printer, and elapsed time.
- JDK 21 or newer
- Maven 3.9+
git clone https://github.com/MooreHaww/bounded-print-queue.gitcd bounded-print-queuemvn packagemvn package runs the tests and builds target\bounded-print-queue.jar. To build without running the tests:
mvn -q package -DskipTestsjava -jar target\bounded-print-queue.jar --help| option | meaning | default |
|---|---|---|
--clients N |
client threads P (positive) | 4 |
--printers N |
printer threads C (positive) | 2 |
--capacity N |
queue capacity K (positive) | 3 |
--jobs N |
jobs per client J (0 or more) | 5 |
--produce-ms N |
max random production delay in ms (0..60000) | 50 |
--print-ms N |
max random printing delay in ms (0..60000) | 100 |
--seed N |
seed for the random delays | 42 |
--trace |
print timestamped events | off |
Values can be written as --jobs 10 or --jobs=10. Clients × jobs may be at most 10,000,000 in total, because each run keeps an audit entry per job. Exit codes: 0 verified OK, 1 verification failed (or the run was interrupted), 2 bad command line (an error message and the usage text are printed).
Examples:
java -jar target\bounded-print-queue.jarjava -jar target\bounded-print-queue.jar --clients 2 --printers 2 --capacity 2 --jobs 4 --produce-ms 5 --print-ms 60 --seed 7 --tracejava -jar target\bounded-print-queue.jar --clients 4 --printers 4 --capacity 3 --jobs 10 --produce-ms 20 --print-ms 100java -jar target\bounded-print-queue.jar --jobs 0java -jar target\bounded-print-queue.jar --capacity 0; $LASTEXITCODESample summary:
Bounded print queue simulation
clients P=2 printers C=2 capacity K=2 jobs per client J=4
produce delay 0..5 ms print delay 0..60 ms seed 7
Results
jobs submitted 8 / 8
jobs printed 8
max queue size 2 (capacity 2)
max printing at once 2 of 2 printers
per printer P1=3 P2=5
elapsed 118.6 ms
VERIFIED OK: every job printed exactly once, FIFO order kept, queue never above K, queue empty at the end, no worker errors.
BoundedPrintQueue stores jobs in a plain circular array (head, tail, count) and uses three fair semaphores:
| semaphore | initial value | counts | who waits on it |
|---|---|---|---|
spaces |
K (capacity) | free slots | put when the queue is full |
items |
0 | stored jobs | take when the queue is empty |
mutex |
1 | binary lock on the array and counters | everyone, briefly |
Order of operations:
put(job): spaces.acquire -> mutex.acquire -> insert at tail -> mutex.release -> items.release
take(): items.acquire -> mutex.acquire -> remove at head -> mutex.release -> spaces.release
At all times, spaces + items plus the number of threads that are between acquiring one counting permit and releasing the other equals K. If a thread is interrupted while waiting for mutex after it already got its counting permit, it releases that permit again before rethrowing, so no permit ever leaks. The queue also checks for overflow and underflow while holding the mutex and throws IllegalStateException if either happens (it never should).
All shared fields are read and written only while holding mutex. A semaphore release() happens-before the next acquire(), which makes every write visible to the next holder without volatile.
- The counting semaphore is always acquired before the mutex. A thread that holds the mutex therefore never waits for anything: it does a constant amount of work and releases it.
- If the order were reversed (mutex first, then
spaces), a client could hold the mutex while waiting for a free slot. No printer could then get the mutex to free one, and that is the classic deadlock. putwaits only onspacesandtakewaits only onitems, and each side releases the other's semaphore, so a blocked client is always woken by a printer'stakeand a blocked printer by a client'sput.- Statistics and tracing use their own binary semaphores, only ever taken inside the queue's mutex or with no other semaphore held, so no cycle can form.
A "two-lock" queue gives put and take their own mutex, so one client and one printer can be inside the queue at the same time. That is safe here, because producers only touch tail, consumers only touch head, and spaces/items already order the handoff of each slot. I kept a single mutex anyway. With two mutexes there is no single count anymore, which removes the overflow/underflow checks, the exact max-size audit and the FULL/EMPTY trace lines. The gain would be unmeasurable: the critical section is a few array operations, while every job spends milliseconds being produced and printed outside it.
These are two different things:
- Queue order is FIFO by construction: a circular array where
takealways removes the oldest job. The audit log checks this on every run (removal order must equal insertion order). - Thread fairness is about which waiting thread gets to go next. The semaphores are created with
fair = true, so permits are handed to waiting threads in the order they started waiting.
What fair semaphores do not guarantee:
- They don't decide which thread arrives first. That is up to the OS scheduler, so two clients that call
put"at the same time" can enter in either order. - Fairness applies to each semaphore separately. A client that gets a free slot (
spaces) first can still reach themutexsecond, so the order of insertion among clients is not guaranteed to match the order in which they got their slots. - Jobs are taken in FIFO order, but they are not necessarily finished in that order: printing times differ, so a short job taken later can finish earlier.
- A fair semaphore prevents starvation among the threads waiting on it, as long as permits keep being released; it doesn't make the overall schedule deterministic. The same
--seedgives the same random delays but not the same interleaving.
The simplest way to tell printers to stop without polling is to send the message through the queue itself. After every client has finished, the driver puts exactly C stop jobs, one per printer. Because the queue is FIFO, every real job comes before every stop job, so a printer that takes a stop job knows no real work is left for it and exits. Exceptions while printing are recorded and the printer keeps going. An exception from the queue's trace observer is recorded by the queue and never escapes put/take. So every printer still consumes its stop job, and shutdown can't get stuck on either kind of failure.
SimulationResult.verify() returns a list of problems, and an empty list means the run was correct:
- every expected job id (
C1-J1…CP-JJ) was printed exactly once: no lost, duplicated or unexpected jobs - the submitted count is P × J, and the queue saw P × J + C insertions
- removal order equals insertion order (FIFO)
- the max observed queue size is ≤ K
- the queue is empty at the end
- no worker thread reported an exception (uncaught exceptions are captured by a handler and reported)
- the queue's observer never threw
The checks that carry the most weight are exactly-once and the submitted count. Printers record completions independently of the queue, so a queue bug that loses or duplicates a job shows up there. The FIFO and max-size checks are cheap guards that mostly confirm the circular-buffer arithmetic. The array has only K slots, and the overflow check would throw before the size could pass K.
mvn testThe JUnit 5 suite runs in a few seconds. Every test that starts threads runs under a timeout enforced from a separate thread, so a deadlock fails the test instead of hanging it.
BoundedPrintQueueTest: rejects null and non-positive capacity; FIFO order; wrap-around of the circular buffer; aputon a full queue blocks (thread stateWAITING) until atake; atakeon an empty queue blocks until aput; an interrupted blockedput/takeleaves the queue usable. Leaks are checked by behaviour: after the interruption, exactly K puts succeed and the next one blocks. This also covers the harder case of an interrupt while waiting for the mutex, after the counting permit was taken. An observer that throws on every call is recorded, and put/take still complete without leaking permits.PrintServiceStressTest: hundreds of full runs over configurations such as K=1 with 8 clients and 8 printers, 16 clients / 2 printers, 2 clients / 16 printers, J=0, and zero delays with heavy contention (12 × 12 threads, 2400 jobs, K=2). Every run must passverify().ConcurrencyBehaviourTest: with slow printers, more than one printer prints at once and the queue reaches size K.SimulationResultVerifyTest:verify()really catches lost, duplicated and unexpected jobs, wrong counts, FIFO violations, overflow, a non-empty queue, worker errors and observer errors.ErrorPathTest: failures injected through a small package-private hook. A client killed by an uncaught exception is reported by the handler and the run still shuts down. A printer that fails one job records it and keeps printing. A failed verification makesMainexit with code 1.MainArgsTest: defaults, both flag syntaxes, the total-jobs cap, and each kind of bad input (exit code 2).ForbiddenConstructsTest: scanssrc/main(with comments and string contents stripped) and fails onsynchronized,wait/notify, locks, conditions, atomics,BlockingQueue, concurrent collections,volatile, spin hints, any otherjava.util.concurrenttype, or Semaphore methods outsideacquire/release/acquireUninterruptibly.
What passing tests do and don't mean. Thread interleavings are chosen by the scheduler, and their number grows explosively. Hundreds of passing stress runs, including extreme setups like K=1 and heavy contention, are evidence that the queue is correct. They are not a proof. Most runs use zero delays and look alike, nothing measures how many distinct interleavings were actually covered, and a rare one may never come up. They are also weakest against memory-visibility bugs. Typical x86 CPUs order memory strongly enough to hide many of them, and they can still appear on weaker hardware such as ARM. The proper tool for testing that is jcstress, which is beyond the scope of this project. The argument that it is correct for every interleaving is the reasoning in "Why it cannot deadlock" and the semaphore invariant above. The tests and the per-run verify() check that the code matches that reasoning.
From an actual run of --clients 2 --printers 2 --capacity 2 --jobs 4 --produce-ms 5 --print-ms 60 --seed 7 --trace (excerpt; ... marks skipped lines). queue lines are printed while holding the queue's mutex, so they are in true queue order. A waiting line followed much later by its done line means the thread was blocked. Tracing does console output inside the critical section, so a traced run is slower and interleaves differently from an untraced one; use it to understand the mechanism, not to measure it.
[ 7.890 ms] P1 waiting to take <- queue is empty: both printers block
[ 14.234 ms] P2 waiting to take
[ 14.452 ms] C1 waiting to put C1-J1
[ 14.556 ms] C2 waiting to put C2-J1
[ 20.034 ms] queue +C1-J1 size 1/2
[ 20.172 ms] queue +C2-J1 size 2/2 FULL
[ 20.389 ms] queue -C1-J1 size 1/2
[ 20.509 ms] P1 take done -> C1-J1
[ 20.590 ms] queue -C2-J1 size 0/2 EMPTY
[ 20.688 ms] P2 take done -> C2-J1
...
[ 30.768 ms] C2 waiting to put C2-J3
[ 30.879 ms] queue +C2-J3 size 2/2 FULL
[ 30.938 ms] C2 put C2-J3 done
[ 31.264 ms] C1 waiting to put C1-J3 <- queue is full: C1 blocks
[ 35.268 ms] C2 waiting to put C2-J4 <- ... and so does C2
[ 47.938 ms] P2 printed C1-J2
[ 48.033 ms] P2 waiting to take
[ 48.089 ms] queue -C2-J2 size 1/2 <- a slot frees up,
[ 48.150 ms] P2 take done -> C2-J2
[ 48.204 ms] queue +C1-J3 size 2/2 FULL <- C1 gets it (17 ms after it started waiting)
[ 48.336 ms] C1 put C1-J3 done
...
[ 69.010 ms] queue -C2-J3 size 1/2
[ 69.072 ms] P1 take done -> C2-J3
[ 69.118 ms] queue +C2-J4 size 2/2 FULL <- C2 finally gets in, 34 ms after it started waiting
[ 69.249 ms] C2 put C2-J4 done
...
[ 72.921 ms] main all clients done, sending 2 stop jobs
...
[ 125.379 ms] queue -STOP-2 size 0/2 EMPTY
[ 125.418 ms] P2 take done -> STOP-2
[ 125.451 ms] P2 stopping
[ 125.497 ms] main all printers stopped
(The <- notes were added for this README.) The done lines are printed after the call returns, so they can show up a little after other threads' queue events. That is normal scheduling, not a bug.
Same workload, --clients 4 --capacity 3 --jobs 10 --produce-ms 20 --print-ms 100 --seed 42, with only the number of printers changed. This was measured on a Windows 11 machine, JDK 21, 3 runs each:
| printers | elapsed (3 runs) | max printing at once |
|---|---|---|
| 1 | 1839.5, 1842.4, 1828.0 ms | 1 |
| 4 | 512.5, 544.1, 513.5 ms | 4 |
4 printers finish the same 40 jobs about 3.5× faster than 1 printer (≈1.84 s → ≈0.52 s). This is the speedup the design allows, because printing happens outside the queue's critical section.
Raw throughput. With all delays set to zero (--clients 4 --printers 4 --capacity 16 --jobs 100000 --produce-ms 0 --print-ms 0), 400,000 jobs were printed and verified in about 2.8 s on my PC, roughly 143,000 jobs per second. That figure covers the whole run, including the audit logging and the statistics bookkeeping, not just the queue. It is one run on one machine and will vary; it is not a benchmark.
src/main/java/printservice/
BoundedPrintQueue.java circular buffer + 3 semaphores, optional audit mode
PrintJob.java immutable job or stop job
Client.java, Printer.java producer and consumer Runnables
PrintService.java starts/joins threads, sends stop jobs, collects results
SimulationResult.java the collected data + verify()
SharedStats.java completions, per-printer counts, errors (Semaphore(1) mutex)
Tracer.java, QueueObserver.java optional timestamped trace
SimulationConfig.java, Main.java, Delays.java
src/test/java/printservice/ JUnit 5 tests (see above)
MIT, see LICENSE.
