← Lessons

quiz vs the machine

Gold1340

Concurrency

The Try Lock Pattern

A non blocking attempt that takes a lock only if it is free right now.

4 min read · core · beat Gold to climb

Lock or move on

The try lock is the zero wait version of a lock. It attempts a single atomic acquire and returns immediately, reporting whether it got the lock.

  • If the lock was free it is now held and the call returns success.
  • If the lock was busy nothing changes and the call returns failure.

The thread never blocks. It decides what to do based on the result.

Where it shines

  • Doing other useful work while a resource is busy instead of stalling.
  • Avoiding deadlock by acquiring multiple locks all or nothing: try each, and if any fails release the rest and restart.
  • Polling rarely contended state where blocking would be wasteful.

The trap

A tight loop of try lock that just spins on failure becomes a busy wait that burns the core. If you find yourself looping forever on a failed try lock, a blocking lock or a backoff is usually better.

Key idea

Try lock makes a single non blocking attempt and reports success or failure, letting a thread choose a different path instead of waiting and enabling all or nothing multi lock acquisition.

Check yourself

Answer to earn rating on the learn ladder.

1. What does try lock do when the lock is already held?

2. How does try lock help acquire several locks safely?

3. What is the danger of looping on a failed try lock?