Implementing Concurrency

Now we have a basic framework for locking and concurrency management; let’s look at three patterns for implementing locking and concurrency in various environments.

Lockable Object Pattern

Some small applications keep their entire domain model in memory. This ability makes business logic easier to program, since you only need to deal with objects in memory (persistence, in this sort of application, can involve anything from serializing the entire object graph to disk to periodically writing changes to a database). The Lockable Object pattern is a simple approach to implementing locking in a nondistributed system where a single instance of a single application handles all changes to the data.

You can implement a simple lockable object using the Java synchronized keyword. As long as all attempts to access the object are synchronized properly, you don’t have to worry about lost updates, dirty reads, or other concurrency problems. Unfortunately, synchronization has a few problems. First, each thread accessing a synchronized object blocks until the object becomes available, potentially tying up large numbers of threads while waiting for time-consuming processing to complete. Second, synchronized doesn’t help if a user needs to hold onto an object across multiple threads: for instance, a web-based update process spread across two or three requests for a servlet.

To create a solution that lasts across threads, we need to be user-aware. For a lockable object, we accomplish ...

Get J2EE Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.