Showing posts with label Concurrency. Show all posts
Showing posts with label Concurrency. Show all posts

Saturday, 24 August 2013

Offline Concurrency Patterns

Master Enterprise Architecture & Java!

Subscribe to Ram N Java for clean, beginner-friendly software architecture tutorials.

👉 Subscribe Now on YouTube

Understanding Offline Concurrency Patterns

In enterprise systems, business transactions often span multiple database transactions, user screens, or long user think times. Standard database transactions cannot be left open across these lengthy interactions without crippling scalability and resource availability.

To resolve this challenge, Martin Fowler cataloged Offline Concurrency Patterns as part of the Patterns of Enterprise Application Architecture (PofEAA). These patterns coordinate concurrent modifications and maintain data consistency across distributed, multi-step business transactions.

The Four Core Offline Concurrency Patterns

1. Optimistic Offline Lock Pattern

Assumes conflicts between concurrent sessions are rare. Instead of locking records beforehand, it allows multiple sessions to view and edit data concurrently. When submitting changes, it checks whether another session has committed changes first (typically using a version number or timestamp). If a conflict is detected, the transaction rolls back gracefully.

2. Pessimistic Offline Lock Pattern

Assumes concurrent conflicts are likely to occur. It prevents concurrency by allowing only one business transaction to acquire an exclusive lock on data for the entire duration of the multi-step transaction, preventing other users from modifying the same data simultaneously.

3. Coarse-Grained Lock Pattern

Locks a whole group of related objects (an aggregate) through a single shared lock instead of locking each individual child entity. For example, acquiring a lock on an entire customer order rather than locking every individual order line item separately.

4. Implicit Lock Pattern

Enforces locking rules transparently through framework or application code rather than relying on manual developer discipline. This ensures locks are consistently acquired and released without forgetting steps across complex workflows.

Recommended Related Videos from Ram N Java

Explore each offline concurrency pattern in depth with these detailed walkthroughs:


Click here to watch in Youtube : https://www.youtube.com/watch?v=9UBuUDL76fI

Click the below Image to Enlarge
Offline Concurrency Patterns














See also:

  • All Design Patterns Links
  • Thursday, 15 August 2013

    Optimistic Offline Lock Design Pattern

    Master Enterprise Architecture & Java!

    Subscribe to Ram N Java for clean, beginner-friendly software architecture tutorials.

    👉 Subscribe Now on YouTube

    What is the Optimistic Offline Lock Pattern?

    The Optimistic Offline Lock Design Pattern belongs to the offline concurrency patterns family in Martin Fowler's Patterns of Enterprise Application Architecture (PofEAA). Its primary goal is to prevent conflicts between concurrent business transactions by detecting a conflict and rolling back the transaction.

    Unlike pessimistic locking—which places strict database or memory locks to block others—optimistic locking operates on the assumption that the chances of conflict between users are low. Rather than locking records early, it lets users read and modify data concurrently, verifying for collisions only at the time of commit.

    1. The Customer Table & Version Column

    The most common implementation associates a version number (or timestamp) with each record in your database table:

    • customer_id: Unique identifier (e.g., 129).
    • first_name & last_name: Customer name fields (e.g., John Doe).
    • items_ordered: Count of items placed by the customer.
    • customer_version: Tracks the current revision of the row (starts at 1).

    2. Step-by-Step Scenario: Martin vs. David

    Let us examine what happens when two independent sessions retrieve and modify the same customer record concurrently:

    1. Both Read Version 1: Martin's session queries customer 129 and holds the row with customer_version = 1. Seconds later, David's session requests the exact same customer and also receives customer_version = 1.
    2. David Commits First: David updates the customer's first name and commits to the database. The database updates the row and automatically increments the version column from 1 to 2.
    3. Martin Tries to Commit: Martin finishes his edits and attempts to write his changes back to the database. However, Martin's session is still carrying the stale customer_version = 1.
    4. Conflict Detected & Rollback: The update query checks WHERE customer_id = 129 AND customer_version = 1. Because the database row is now at version 2, zero rows match. The system detects the concurrency collision, fails the update, and rolls back Martin's transaction to protect data integrity.

    3. Key Takeaways

    • High Throughput: Because no physical locks are held while users think or fill out forms, system scalability remains high.
    • Stale Data Protection: The version column ensures no user accidentally overwrites another user's unread changes.
    • Framework Support: Modern persistence frameworks like Hibernate and JPA provide native support for this pattern using the @Version annotation.

    Recommended Related Videos from Ram N Java

    Continue exploring enterprise concurrency and locking strategies with these tutorials:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=ggfMCGKX3r8

    Click the below Image to Enlarge
    Optimistic Offline Lock Design Pattern














    See also:

  • All Design Patterns Links
  • Saturday, 10 August 2013

    Double-checked locking Design Pattern - Implementation

    Master Java Multithreading & Patterns!

    Subscribe to Ram N Java for clean, beginner-friendly software architecture tutorials.

    👉 Subscribe Now on YouTube

    Implementing Double-Checked Locking in Java

    Synchronizing an entire method call like getInstance() creates a performance bottleneck because every single thread has to acquire a lock, even after the singleton object has already been created. The Double-Checked Locking Design Pattern aims to solve this by acquiring the lock only when initialization is truly required.

    1. The Implementation Structure

    Instead of placing the synchronized keyword at the method level, synchronization is moved inside the method with two checks:

    • First Check: Verify if instance == null without locking. If it is already initialized, return it immediately without overhead.
    • Synchronized Block: If instance is null, enter a synchronized block to ensure only one thread can proceed.
    • Second Check: Check again if instance == null inside the synchronized block before allocating the object.

    2. Step-by-Step Thread Execution Flow

    Here is what happens when two threads (Thread A and Thread B) enter simultaneously:

    1. Thread A arrives: Evaluates instance == null (true) and acquires the lock on the synchronized block.
    2. Thread B arrives: Evaluates instance == null (true) and attempts to enter the synchronized block, but gets blocked because Thread A holds the lock.
    3. Thread A creates instance: Re-checks instance == null inside the block, initializes the new object, exits the synchronized block, and returns the reference.
    4. Thread B resumes: Enters the synchronized block, evaluates the second check instance == null (now false!), skips initialization, and safely returns the existing instance created by Thread A.

    3. The Reality: Why It Can Fail

    While the logic appears foolproof in theory, in practice it can break without proper memory barriers:

    • Out-of-Order Writes: The Java Memory Model allows compilers and processors to reorder instructions for performance. An object reference can be assigned before the constructor finishes executing.
    • Anti-Pattern Classification: Because unsynchronized reader threads can see partially initialized objects, double-checked locking is considered an anti-pattern unless used with the volatile keyword.

    Recommended Related Videos from Ram N Java

    Explore these multithreading tutorials to learn more about synchronization and locking:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=nL2n_NCl7TA

    Click the below Image to Enlarge
    Double-checked locking Design Pattern - Implementation














    See also:

  • All Design Patterns Links
  • Monday, 5 August 2013

    Reactor Design Pattern vs Observer Design Pattern

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

    Subscribe on YouTube

    Reactor Pattern vs. Observer Pattern: Architectural Comparison

    Both the Reactor Design Pattern and the Observer Design Pattern handle event notifications and state changes, but they target fundamentally different architectural layers and scalability challenges.

    While the Observer pattern operates primarily at the in-memory application layer to synchronize dependent objects, the Reactor pattern addresses high-concurrency I/O multiplexing and non-blocking network communication across multiple service handles.

    Key Architectural Differences

    • Purpose & Scope:
      • Observer Pattern: Maintains consistency between domain objects (one-to-many relationship) typically in a single-threaded or synchronous in-process context.
      • Reactor Pattern: Demultiplexes and dispatches incoming events, requests, or network I/O streams using an event loop to dedicated event handlers.
    • Core Components:
      • Observer: Subject, Observer interface, and Concrete Observers.
      • Reactor: Initiation Dispatcher (Reactor loop), Synchronous Event Demultiplexer, Handle, and Event Handlers.
    • Concurrency & Execution Model:
      • Observer: Notifications are directly broadcast to observers, often executing in the caller thread.
      • Reactor: Utilizes a non-blocking single-threaded event loop (or a worker thread pool) to handle thousands of concurrent client connections efficiently.

    When Should You Use Each Pattern?

    Choose the Observer Pattern when:

    • You need to keep UI components updated with underlying data model changes (e.g., MVC architectures).
    • Business entities must react to state transitions, such as price alert systems or order status updates.

    Choose the Reactor Pattern when:

    • You are building scalable, non-blocking network servers, web frameworks (like Netty or Node.js), or event-driven microservices.
    • High throughput and low-latency I/O handling are required without spinning up a thread per connection.

    Related Design Pattern Tutorials to Watch Next


    Click here to watch in Youtube : https://www.youtube.com/watch?v=1lH3Kabhc1Y

    Click the below Image to Enlarge
    Reactor Design Pattern vs Observer Design Pattern

    Tutorials