Skip to content

Coarse-Grained Lock Pattern — Lock Groups of Objects

DodaTech Updated 2026-06-29 3 min read

In this tutorial, you'll learn how Coarse-Grained Lock simplifies concurrency by locking groups of related objects with a single lock.

What You'll Learn

how Coarse-Grained Lock simplifies concurrency by locking groups of related objects with a single lock.

Why It Matters

Fine-grained locks are hard to manage and prone to deadlocks. Coarse-grained locks simplify the system.

Real-World Use

Aggregate root as lock owner, shared parent lock, and database table-level locks.

The Coarse-Grained Lock Pattern

The Coarse-Grained Lock pattern addresses a specific recurring design problem by providing a reusable solution structure. Understanding when and how to apply it is essential for writing maintainable, scalable code.

Key Concepts

  • Registry/Tracking: Coarse-Grained Lock maintains a registry of objects or operations.
  • Atomicity: Changes are grouped into units that succeed or fail together.
  • Isolation: Each unit operates independently.
  • Consistency: The pattern ensures data integrity across operations.

Structure

The following diagram shows the structure of this pattern:

classDiagram
    class CoarseGrainedLock {
        +findById()
        +findAll()
        +save()
        +delete()
    }
    class Database { +query() }
    Client --> CoarseGrainedLock
    CoarseGrainedLock --> Database

Implementation

from typing import List, Optional, Dict
from dataclasses import dataclass

@dataclass
class Entity:
    id: int
    name: str
    email: str

class CoarseGrainedLock:
    def __init__(self, connection: Dict):
        self._conn = connection

    def find_by_id(self, entity_id: int) -> Optional[Entity]:
        print(f"SELECT * FROM entities WHERE id = {entity_id}")
        return Entity(entity_id, "Alice", "alice@example.com")

    def find_all(self) -> List[Entity]:
        print("SELECT * FROM entities")
        return [Entity(1, "Alice", "a@x.com"), Entity(2, "Bob", "b@x.com")]

    def save(self, entity: Entity) -> Entity:
        if entity.id:
            print(f"UPDATE entities SET ... WHERE id = {entity.id}")
        else:
            print("INSERT INTO entities ...")
        return entity

    def delete(self, entity_id: int):
        print(f"DELETE FROM entities WHERE id = {entity_id}")

repo = CoarseGrainedLock({"host": "localhost", "db": "test"})
user = repo.find_by_id(1)
print(f"Found: {user.name}")
users = repo.find_all()
print(f"Total: {len(users)}")
repo.delete(1)

Expected output:

SELECT * FROM entities WHERE id = 1
Found: Alice
SELECT * FROM entities
Total: 2
DELETE FROM entities WHERE id = 1

Key Participants

  • Coarse-Grained Lock: Coordinates tracking and persistence of changes.
  • Entity: The domain object being tracked.
  • Client: Code that uses the Coarse-Grained Lock.
  • Data Mapper: Handles actual database operations.

Real-World Examples

  • DodaTech uses this pattern internally for consistent cross-cutting concerns.
  • Major frameworks and libraries implement this pattern as a core architectural element.
  • Production systems at scale depend on this pattern for reliability.
  • Optimistic Lock

  • Pessimistic Lock

  • Aggregate Root

  • Design Patterns — the complete patterns catalog.

Pros and Cons

Pros Cons
Provides a clean, reusable solution to a common problem Can introduce unnecessary complexity for simple problems
Improves code maintainability and readability May reduce performance due to additional abstraction layers
Establishes a shared vocabulary for developers Requires team familiarity with the pattern
Reduces development time through proven solutions Overuse can lead to overly abstract, hard-to-follow code

Common Mistakes

  1. **Over-engineering: Applying Coarse-Grained Lock where a simpler solution suffices, adding unnecessary complexity.

  2. **Wrong granularity: Implementing Coarse-Grained Lock at the wrong level of abstraction.

  3. **Thread Safety ignored: Using Coarse-Grained Lock in concurrent context without proper synchronization.

  4. **Tight coupling: Violating the pattern intent by creating hidden dependencies.

  5. **Premature optimization: Introducing Coarse-Grained Lock before there is evidence it is needed.

Practice Questions

  1. What problem does the Coarse-Grained Lock pattern solve? Describe a real-world scenario where using it improves code quality.

  2. How does Coarse-Grained Lock differ from alternative approaches? What are the trade-offs?

  3. What testing Strategy would you use for code that implements Coarse-Grained Lock?

  4. How would you refactor legacy code to introduce Coarse-Grained Lock?

  5. When should you NOT use Coarse-Grained Lock? Describe scenarios where it adds unnecessary complexity.

Challenge

Implement a complete Coarse-Grained Lock example in Python with unit tests. Include error handling, edge cases (empty data, null values, concurrent access), and a performance comparison against a simpler alternative. Document your design decisions.

Real-World Task

Find a section of code in your current project that could benefit from the Coarse-Grained Lock pattern. Refactor it, write tests, and measure the improvement in testability, coupling, and cohesion.

Security Tip: When implementing Coarse-Grained Lock, ensure proper input validation, avoid exposing internal state, and follow Least Privilege. At DodaTech, all implementations undergo security review.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro