Step 12 of 21 · 4 minutes

One Printer, Many Jobs

The Scenario

The PDF generation service can only handle one document at a time. When multiple jobs print simultaneously, we get corrupted documents.

We need exclusive access to shared resources.

The Challenge

How do we ensure only one job can use a shared resource at a time?

The Solution

Use a Mutex (mutually exclusive lock) to protect shared resources:


@Job(mutex = "pdf-printer")
public void generatePDF(Statement statement) {
    pdfService.print(statement); // Only one job runs at a time
}

Jobs with the same mutex are processed one at a time. Others wait in AWAITING state until the mutex is released.

You can also use dynamic mutexes: @Job(mutex = "printer/%0") creates one mutex per printer ID!

Read the documentation →

Try It Yourself

Generate multiple statements and watch them process one at a time, even though multiple workers are available.
You need to log in to perform write operations. You can still view the code solution and dashboard.
1
Generate Multiple Statements