Patternadvanced
Implicit lock
Also called Implicit Lock, automatic locking, locking mapper, framework-managed locks.
An implicit lock puts the code that takes and checks the offline locks into the framework, the mappers or a layer supertype, so that no application script can forget a lock.
- Family
- architectural
- Intent
- Allow framework or layer supertype code to acquire offline locks.
Intent
An implicit lock "Allows framework or layer supertype code to acquire offline locks."1 The application scripts load and save the objects as usual. The shared code below them takes the locks, checks the versions and releases the locks.
Problem
"The key to any locking scheme is that there are no gaps in its use."1 One script that forgets to take a lock, or to check a version, makes the whole scheme useless for the data that the script changes. "Generally, if an item might be locked anywhere it must be locked everywhere."1
The other errors are as bad. A script that does not release its locks keeps the other users out: "Not releasing locks won't corrupt your record data, but it will eventually bring productivity to a halt."1 These errors are hard to find, because they show only when two users work at the same time. "Because offline concurrency management is difficult to test, such errors might go undetected by all of your test suites."1
Solution
"One solution is to not allow developers to make such a mistake. Locking tasks that cannot be overlooked should be handled not explicitly by developers but implicitly by the application."1 The places for this code are the framework, the Layer supertype of the domain objects or the mappers, and generated code.1
The parts are:
- The locking mapper. A mapper with the same interface as the plain mapper. Its
findtakes the lock before it loads the object, and itsupdatechecks the version. It is a Decorator pattern around the plain mapper.2 - The business transaction. The framework creates it for each business transaction. It gives the scripts only the locking mapper, and it releases all the locks at the end, also when the business transaction fails.
- The lock manager or the version check. The lock itself is a Pessimistic offline lock or an Optimistic offline lock. The implicit lock only decides where the calls are.
application script customer = tx.customers.find(1) (no lock call)
|
locking mapper lock manager: acquire "customer 1"
| then the plain mapper: find(1)
plain mapper SELECT ... FROM customer WHERE id = 1
|
business transaction at the end: lock manager: release all
In the following program, find_for_edit is the framework code. It takes the lock, so the script raise_credit gets a lock without a lock call of its own.
locks = {}
table = {1: {"name": "Acme Ltd", "credit": 500}}
def find_for_edit(owner, customer_id): # framework code: every find for edit takes the lock
holder = locks.setdefault(customer_id, owner)
if holder != owner:
raise PermissionError(f"customer {customer_id} is locked by {holder}")
return dict(table[customer_id])
def raise_credit(owner, amount): # application code: it has no lock call
try:
row = find_for_edit(owner, 1)
except PermissionError as e:
return f"refused, {e}"
row["credit"] += amount
table[1] = row
return "ok"
ann = find_for_edit("ann", 1)
print("ann edits:", ann["name"])
print("bob:", raise_credit("bob", 100))
ann edits: Acme Ltd
bob: refused, customer 1 is locked by ann
Example
Each example file has a lock manager, a plain mapper for customers, and a locking mapper that wraps it. The framework gives each business transaction a locking mapper, and releases its locks when it ends. Two scripts use the mapper: one renames a customer across two requests, and one raises the credit. Neither script calls the lock manager. Ann opens customer 1 to rename it, so the mapper takes the lock for Ann. Bob runs the credit script on the same customer and is refused. Ann saves, and the end of the business transaction releases the lock. Bob runs the script again and it succeeds. At the end, both changes are in the database, the mapper took 2 locks, and no lock is left.
class LockError(Exception):
pass
class LockManager:
"""Exclusive locks for business transactions, kept until the transaction ends."""
def __init__(self):
self.held = {}
def acquire(self, resource, owner):
holder = self.held.setdefault(resource, owner)
if holder != owner:
raise LockError(f"{resource} is locked by {holder}")
def release_all(self, owner):
for resource in [r for r, o in self.held.items() if o == owner]:
del self.held[resource]
class CustomerMapper:
def __init__(self, rows):
self.rows = rows
def find(self, customer_id):
return dict(self.rows[customer_id], id=customer_id)
def update(self, customer):
self.rows[customer["id"]] = {"name": customer["name"], "credit": customer["credit"]}
class LockingMapper:
"""Wraps a mapper. Each find takes the lock first, so the application scripts never call the lock manager."""
taken = 0
def __init__(self, mapper, locks, owner):
self.mapper, self.locks, self.owner = mapper, locks, owner
def find(self, customer_id):
self.locks.acquire(f"customer {customer_id}", self.owner)
LockingMapper.taken += 1
return self.mapper.find(customer_id)
def update(self, customer):
self.mapper.update(customer)
rows = {1: {"name": "Acme Ltd", "credit": 500}}
locks = LockManager()
plain = CustomerMapper(rows)
class BusinessTransaction:
"""The framework gives each business transaction a locking mapper and releases its locks at the end."""
def __init__(self, owner):
self.owner = owner
self.customers = LockingMapper(plain, locks, owner)
def end(self):
locks.release_all(self.owner)
# The application scripts. Not one of them calls the lock manager.
def open_for_rename(tx, customer_id):
return tx.customers.find(customer_id)
def save_rename(tx, customer, name):
customer["name"] = name
tx.customers.update(customer)
tx.end()
def raise_credit(tx, customer_id, amount):
customer = tx.customers.find(customer_id)
customer["credit"] += amount
tx.customers.update(customer)
tx.end()
return customer["credit"]
def run_raise_credit(who, tx):
try:
credit = raise_credit(tx, 1, 100)
print(f"{who} raises the credit of customer 1: ok, credit {credit}")
except LockError as e:
tx.end()
print(f"{who} raises the credit of customer 1: refused: {e}")
ann, bob = BusinessTransaction("ann"), BusinessTransaction("bob")
customer = open_for_rename(ann, 1)
print("ann opens customer 1 to rename it:", customer["name"])
run_raise_credit("bob", bob)
save_rename(ann, customer, "Acme Group")
print("ann saves the new name: Acme Group")
run_raise_credit("bob", bob)
print("final:", plain.find(1)["name"], "with credit", plain.find(1)["credit"])
print("locks taken by the mapper:", LockingMapper.taken, "locks held now:", len(locks.held))
ann opens customer 1 to rename it: Acme Ltd
bob raises the credit of customer 1: refused: customer 1 is locked by ann
ann saves the new name: Acme Group
bob raises the credit of customer 1: ok, credit 600
final: Acme Group with credit 600
locks taken by the mapper: 2 locks held now: 0
- Verdict: idiom.
LockingMapperwraps the plain mapper and has the same methods, so the application scripts do not know that a lock is taken.BusinessTransactiongives each business transaction its locking mapper, andendreleases its locks. run_raise_creditalso callsendwhen the lock is refused, so a business transaction that fails keeps no locks.
import java.util.HashMap;
import java.util.Map;
public class Main {
static class LockException extends Exception {
LockException(String message) {
super(message);
}
}
// Exclusive locks for business transactions, kept until the transaction ends.
static class LockManager {
final Map<String, String> held = new HashMap<>();
void acquire(String resource, String owner) throws LockException {
String holder = held.putIfAbsent(resource, owner);
if (holder != null && !holder.equals(owner)) {
throw new LockException(resource + " is locked by " + holder);
}
}
void releaseAll(String owner) {
held.values().removeIf(o -> o.equals(owner));
}
}
static class Customer {
final int id;
String name;
int credit;
Customer(int id, String name, int credit) {
this.id = id;
this.name = name;
this.credit = credit;
}
}
interface Mapper {
Customer find(int id) throws LockException;
void update(Customer customer);
}
static class CustomerMapper implements Mapper {
final Map<Integer, Customer> rows = new HashMap<>();
public Customer find(int id) {
Customer row = rows.get(id);
return new Customer(id, row.name, row.credit);
}
public void update(Customer c) {
rows.put(c.id, new Customer(c.id, c.name, c.credit));
}
}
// Wraps a mapper. Each find takes the lock first, so the application scripts never call the lock manager.
static class LockingMapper implements Mapper {
static int taken = 0;
final Mapper mapper;
final LockManager locks;
final String owner;
LockingMapper(Mapper mapper, LockManager locks, String owner) {
this.mapper = mapper;
this.locks = locks;
this.owner = owner;
}
public Customer find(int id) throws LockException {
locks.acquire("customer " + id, owner);
taken++;
return mapper.find(id);
}
public void update(Customer customer) {
mapper.update(customer);
}
}
static final LockManager locks = new LockManager();
static final CustomerMapper plain = new CustomerMapper();
// The framework gives each business transaction a locking mapper and releases its locks at the end.
static class BusinessTransaction {
final String owner;
final Mapper customers;
BusinessTransaction(String owner) {
this.owner = owner;
this.customers = new LockingMapper(plain, locks, owner);
}
void end() {
locks.releaseAll(owner);
}
}
// The application scripts. Not one of them calls the lock manager.
static Customer openForRename(BusinessTransaction tx, int id) throws LockException {
return tx.customers.find(id);
}
static void saveRename(BusinessTransaction tx, Customer customer, String name) {
customer.name = name;
tx.customers.update(customer);
tx.end();
}
static int raiseCredit(BusinessTransaction tx, int id, int amount) throws LockException {
Customer customer = tx.customers.find(id);
customer.credit += amount;
tx.customers.update(customer);
tx.end();
return customer.credit;
}
static void runRaiseCredit(String who, BusinessTransaction tx) {
try {
int credit = raiseCredit(tx, 1, 100);
System.out.println(who + " raises the credit of customer 1: ok, credit " + credit);
} catch (LockException e) {
tx.end();
System.out.println(who + " raises the credit of customer 1: refused: " + e.getMessage());
}
}
public static void main(String[] args) throws LockException {
plain.rows.put(1, new Customer(1, "Acme Ltd", 500));
BusinessTransaction ann = new BusinessTransaction("ann");
BusinessTransaction bob = new BusinessTransaction("bob");
Customer customer = openForRename(ann, 1);
System.out.println("ann opens customer 1 to rename it: " + customer.name);
runRaiseCredit("bob", bob);
saveRename(ann, customer, "Acme Group");
System.out.println("ann saves the new name: Acme Group");
runRaiseCredit("bob", bob);
Customer last = plain.find(1);
System.out.println("final: " + last.name + " with credit " + last.credit);
System.out.println("locks taken by the mapper: " + LockingMapper.taken + " locks held now: " + locks.held.size());
}
}
ann opens customer 1 to rename it: Acme Ltd
bob raises the credit of customer 1: refused: customer 1 is locked by ann
ann saves the new name: Acme Group
bob raises the credit of customer 1: ok, credit 600
final: Acme Group with credit 600
locks taken by the mapper: 2 locks held now: 0
- Verdict: idiom.
Mapperis the interface, andLockingMapperis a decorator that implements it. The scripts get aMapperfrom the business transaction, so they cannot call the plain mapper by mistake. putIfAbsentchecks and takes the lock in one call, andreleaseAllremoves the locks of one owner withremoveIf.
class LockError extends Error {}
// Exclusive locks for business transactions, kept until the transaction ends.
class LockManager {
constructor() {
this.held = new Map();
}
acquire(resource, owner) {
if (!this.held.has(resource)) this.held.set(resource, owner);
const holder = this.held.get(resource);
if (holder !== owner) throw new LockError(`${resource} is locked by ${holder}`);
}
releaseAll(owner) {
for (const [r, o] of [...this.held]) if (o === owner) this.held.delete(r);
}
}
class CustomerMapper {
constructor(rows) {
this.rows = rows;
}
find(id) {
return { id, ...this.rows.get(id) };
}
update(customer) {
this.rows.set(customer.id, { name: customer.name, credit: customer.credit });
}
}
// Wraps a mapper. Each find takes the lock first, so the application scripts never call the lock manager.
class LockingMapper {
static taken = 0;
constructor(mapper, locks, owner) {
this.mapper = mapper;
this.locks = locks;
this.owner = owner;
}
find(id) {
this.locks.acquire(`customer ${id}`, this.owner);
LockingMapper.taken++;
return this.mapper.find(id);
}
update(customer) {
this.mapper.update(customer);
}
}
const rows = new Map([[1, { name: "Acme Ltd", credit: 500 }]]);
const locks = new LockManager();
const plain = new CustomerMapper(rows);
// The framework gives each business transaction a locking mapper and releases its locks at the end.
class BusinessTransaction {
constructor(owner) {
this.owner = owner;
this.customers = new LockingMapper(plain, locks, owner);
}
end() {
locks.releaseAll(this.owner);
}
}
// The application scripts. Not one of them calls the lock manager.
function openForRename(tx, id) {
return tx.customers.find(id);
}
function saveRename(tx, customer, name) {
customer.name = name;
tx.customers.update(customer);
tx.end();
}
function raiseCredit(tx, id, amount) {
const customer = tx.customers.find(id);
customer.credit += amount;
tx.customers.update(customer);
tx.end();
return customer.credit;
}
function runRaiseCredit(who, tx) {
try {
const credit = raiseCredit(tx, 1, 100);
console.log(`${who} raises the credit of customer 1: ok, credit ${credit}`);
} catch (e) {
if (!(e instanceof LockError)) throw e;
tx.end();
console.log(`${who} raises the credit of customer 1: refused: ${e.message}`);
}
}
const ann = new BusinessTransaction("ann");
const bob = new BusinessTransaction("bob");
const customer = openForRename(ann, 1);
console.log("ann opens customer 1 to rename it:", customer.name);
runRaiseCredit("bob", bob);
saveRename(ann, customer, "Acme Group");
console.log("ann saves the new name: Acme Group");
runRaiseCredit("bob", bob);
const last = plain.find(1);
console.log("final:", last.name, "with credit", last.credit);
console.log("locks taken by the mapper:", LockingMapper.taken, "locks held now:", locks.held.size);
ann opens customer 1 to rename it: Acme Ltd
bob raises the credit of customer 1: refused: customer 1 is locked by ann
ann saves the new name: Acme Group
bob raises the credit of customer 1: ok, credit 600
final: Acme Group with credit 600
locks taken by the mapper: 2 locks held now: 0
- Verdict: idiom.
LockingMapperhas the same methods asCustomerMapper, so the scripts use it with no change. JavaScript has no interfaces, and the two classes only need methods with the same names. LockErrorextendsError, andrunRaiseCreditchecks the class withinstanceof, so other errors are not caught.
package main
import (
"errors"
"fmt"
)
// LockError reports a lock that another business transaction holds.
type LockError struct {
resource, holder string
}
func (e *LockError) Error() string {
return e.resource + " is locked by " + e.holder
}
// lockManager keeps exclusive locks for business transactions until the transaction ends.
type lockManager struct {
held map[string]string
}
func (m *lockManager) acquire(resource, owner string) error {
holder, ok := m.held[resource]
if !ok {
m.held[resource] = owner
return nil
}
if holder != owner {
return &LockError{resource, holder}
}
return nil
}
func (m *lockManager) releaseAll(owner string) {
for r, o := range m.held {
if o == owner {
delete(m.held, r)
}
}
}
type customer struct {
id int
name string
credit int
}
type mapper interface {
find(id int) (customer, error)
update(c customer)
}
type customerMapper struct {
rows map[int]customer
}
func (m *customerMapper) find(id int) (customer, error) { return m.rows[id], nil }
func (m *customerMapper) update(c customer) { m.rows[c.id] = c }
var taken = 0
// lockingMapper wraps a mapper. Each find takes the lock first, so the application scripts never call the lock manager.
type lockingMapper struct {
mapper mapper
locks *lockManager
owner string
}
func (m *lockingMapper) find(id int) (customer, error) {
if err := m.locks.acquire(fmt.Sprintf("customer %d", id), m.owner); err != nil {
return customer{}, err
}
taken++
return m.mapper.find(id)
}
func (m *lockingMapper) update(c customer) { m.mapper.update(c) }
var (
locks = &lockManager{held: map[string]string{}}
plain = &customerMapper{rows: map[int]customer{1: {id: 1, name: "Acme Ltd", credit: 500}}}
)
// businessTransaction is what the framework gives to each business transaction:
// a locking mapper, and the release of its locks at the end.
type businessTransaction struct {
owner string
customers mapper
}
func newBusinessTransaction(owner string) *businessTransaction {
return &businessTransaction{owner, &lockingMapper{plain, locks, owner}}
}
func (tx *businessTransaction) end() { locks.releaseAll(tx.owner) }
// The application scripts. Not one of them calls the lock manager.
func openForRename(tx *businessTransaction, id int) (customer, error) {
return tx.customers.find(id)
}
func saveRename(tx *businessTransaction, c customer, name string) {
c.name = name
tx.customers.update(c)
tx.end()
}
func raiseCredit(tx *businessTransaction, id, amount int) (int, error) {
c, err := tx.customers.find(id)
if err != nil {
return 0, err
}
c.credit += amount
tx.customers.update(c)
tx.end()
return c.credit, nil
}
func runRaiseCredit(who string, tx *businessTransaction) {
credit, err := raiseCredit(tx, 1, 100)
var lockErr *LockError
if errors.As(err, &lockErr) {
tx.end()
fmt.Printf("%s raises the credit of customer 1: refused: %v\n", who, err)
return
}
fmt.Printf("%s raises the credit of customer 1: ok, credit %d\n", who, credit)
}
func main() {
ann, bob := newBusinessTransaction("ann"), newBusinessTransaction("bob")
c, err := openForRename(ann, 1)
if err != nil {
panic(err)
}
fmt.Println("ann opens customer 1 to rename it:", c.name)
runRaiseCredit("bob", bob)
saveRename(ann, c, "Acme Group")
fmt.Println("ann saves the new name: Acme Group")
runRaiseCredit("bob", bob)
last, _ := plain.find(1)
fmt.Println("final:", last.name, "with credit", last.credit)
fmt.Println("locks taken by the mapper:", taken, "locks held now:", len(locks.held))
}
ann opens customer 1 to rename it: Acme Ltd
bob raises the credit of customer 1: refused: customer 1 is locked by ann
ann saves the new name: Acme Group
bob raises the credit of customer 1: ok, credit 600
final: Acme Group with credit 600
locks taken by the mapper: 2 locks held now: 0
- Verdict: idiom. The
mapperinterface hasfindandupdate, andlockingMapperwraps anothermapper. The scripts hold the interface, so they do not know which mapper they use. runRaiseCredituseserrors.Asto find a*LockErrorin the error that it gets.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
// Exclusive locks for business transactions, kept until the transaction ends.
#[derive(Default)]
struct LockManager {
held: HashMap<String, String>,
}
impl LockManager {
fn acquire(&mut self, resource: &str, owner: &str) -> Result<(), String> {
let holder = self.held.entry(resource.to_string()).or_insert_with(|| owner.to_string());
if holder.as_str() != owner {
return Err(format!("{} is locked by {}", resource, holder));
}
Ok(())
}
fn release_all(&mut self, owner: &str) {
self.held.retain(|_, o| o.as_str() != owner);
}
}
#[derive(Clone)]
struct Customer {
id: u32,
name: String,
credit: i64,
}
trait Mapper {
fn find(&self, id: u32) -> Result<Customer, String>;
fn update(&self, c: &Customer);
}
struct CustomerMapper {
rows: RefCell<HashMap<u32, Customer>>,
}
impl Mapper for CustomerMapper {
fn find(&self, id: u32) -> Result<Customer, String> {
Ok(self.rows.borrow()[&id].clone())
}
fn update(&self, c: &Customer) {
self.rows.borrow_mut().insert(c.id, c.clone());
}
}
// Wraps a mapper. Each find takes the lock first, so the application scripts never call the lock manager.
struct LockingMapper {
mapper: Rc<CustomerMapper>,
locks: Rc<RefCell<LockManager>>,
owner: String,
taken: Rc<RefCell<u32>>,
}
impl Mapper for LockingMapper {
fn find(&self, id: u32) -> Result<Customer, String> {
self.locks.borrow_mut().acquire(&format!("customer {}", id), &self.owner)?;
*self.taken.borrow_mut() += 1;
self.mapper.find(id)
}
fn update(&self, c: &Customer) {
self.mapper.update(c);
}
}
// The framework gives each business transaction a locking mapper and releases its locks at the end.
struct BusinessTransaction {
owner: String,
customers: Box<dyn Mapper>,
locks: Rc<RefCell<LockManager>>,
}
impl BusinessTransaction {
fn end(&self) {
self.locks.borrow_mut().release_all(&self.owner);
}
}
// The application scripts. Not one of them calls the lock manager.
fn open_for_rename(tx: &BusinessTransaction, id: u32) -> Result<Customer, String> {
tx.customers.find(id)
}
fn save_rename(tx: &BusinessTransaction, mut customer: Customer, name: &str) {
customer.name = name.to_string();
tx.customers.update(&customer);
tx.end();
}
fn raise_credit(tx: &BusinessTransaction, id: u32, amount: i64) -> Result<i64, String> {
let mut customer = tx.customers.find(id)?;
customer.credit += amount;
tx.customers.update(&customer);
tx.end();
Ok(customer.credit)
}
fn run_raise_credit(who: &str, tx: &BusinessTransaction) {
match raise_credit(tx, 1, 100) {
Ok(credit) => println!("{} raises the credit of customer 1: ok, credit {}", who, credit),
Err(e) => {
tx.end();
println!("{} raises the credit of customer 1: refused: {}", who, e);
}
}
}
fn main() {
let plain = Rc::new(CustomerMapper { rows: RefCell::new(HashMap::new()) });
plain.update(&Customer { id: 1, name: "Acme Ltd".to_string(), credit: 500 });
let locks = Rc::new(RefCell::new(LockManager::default()));
let taken = Rc::new(RefCell::new(0));
let begin = |owner: &str| BusinessTransaction {
owner: owner.to_string(),
customers: Box::new(LockingMapper {
mapper: Rc::clone(&plain),
locks: Rc::clone(&locks),
owner: owner.to_string(),
taken: Rc::clone(&taken),
}),
locks: Rc::clone(&locks),
};
let ann = begin("ann");
let bob = begin("bob");
let customer = open_for_rename(&ann, 1).expect("ann gets the lock");
println!("ann opens customer 1 to rename it: {}", customer.name);
run_raise_credit("bob", &bob);
save_rename(&ann, customer, "Acme Group");
println!("ann saves the new name: Acme Group");
run_raise_credit("bob", &bob);
let last = plain.find(1).unwrap();
println!("final: {} with credit {}", last.name, last.credit);
println!("locks taken by the mapper: {} locks held now: {}", taken.borrow(), locks.borrow().held.len());
}
ann opens customer 1 to rename it: Acme Ltd
bob raises the credit of customer 1: refused: customer 1 is locked by ann
ann saves the new name: Acme Group
bob raises the credit of customer 1: ok, credit 600
final: Acme Group with credit 600
locks taken by the mapper: 2 locks held now: 0
- Verdict: idiom.
Mapperis a trait, and the business transaction holds aBox<dyn Mapper>, so the scripts can only use the locking mapper. The lock manager and the plain mapper are shared withRc<RefCell<...>>. finduses the?operator, so a refused lock returns from the script before it reads the row.
Consequences
Benefits.
- No gaps. Each load through the mapper takes the lock, so a new script gets the locks with no extra code.
- Locks are released. The framework releases the locks at the end of each business transaction, so no script can forget it.
- Simpler scripts. The application code shows the business logic and not the locking.
- One place to change. A change of the locking strategy, such as a new timeout, goes into one place.
Liabilities.
Explicit locks have gaps. In the following program, each script takes its own locks. The script that raises the credit was written later, and it has no lock call. It runs while Ann holds the lock, and the save of Ann then writes over its change.
This code runs but gives a wrong answer on purpose.
locks = {}
table = {1: {"name": "Acme Ltd", "credit": 500}}
def open_for_rename(owner): # this script takes its lock
if locks.setdefault(1, owner) != owner:
raise PermissionError("customer 1 is locked")
return dict(table[1])
def raise_credit(amount): # Wrong: this script was written later, and it has no lock call
row = dict(table[1])
row["credit"] += amount
table[1] = row
ann = open_for_rename("ann") # ann holds the lock and edits the name
raise_credit(100) # this runs while ann holds the lock
ann["name"] = "Acme Group"
table[1] = ann # ann saves the copy that ann read
locks.clear()
print("final:", table[1])
print("the credit change is lost:", table[1]["credit"] == 500)
final: {'name': 'Acme Group', 'credit': 500}
the credit change is lost: True
Put the lock into the mapper that each script uses, and do not give the scripts the plain mapper.
Hidden locks can surprise. A developer who does not know that a load takes a lock can load too much and lock out other users, or fail to handle a refused lock. The developers must still know which loads take locks and that a lock can fail.
Not all locks fit a mapper. A lock of a group, such as a Coarse-grained lock, or a lock that depends on the use case, can need more knowledge than the mapper has.
When not to use it
When the application is small. With a few scripts and one developer, explicit lock calls are easy to see and to review.
When the framework already does it. Many object-relational mappers already check a version column on each save. Use that, and do not add a second layer.
Variants and related patterns
Implicit optimistic lock. The Layer supertype or the mapper keeps the version of each object that it loads, and puts the version check into each UPDATE and DELETE. This is the most common form, because the mapper writes all the SQL.2
Implicit pessimistic lock. A locking mapper takes the lock in each find, as in the example. A pessimistic lock on each load can lock more than the business transaction needs, so the mapper may need a separate find for the cases that only read.
Related patterns. The lock itself is an Optimistic offline lock or a Pessimistic offline lock. The locking mapper is a Decorator pattern of a Data Mapper. A Unit of Work is a good place to check the versions and to release the locks at commit. A framework that calls the application code, and not the other way round, is an example of Inversion of control.
Known uses
- Jakarta Persistence. "The persistence provider is required to perform optimistic locking automatically for every entity with a version".3 The application marks the version field once, and the provider checks it on each update.
- Ruby on Rails. When the table has a
lock_versioncolumn, Active Record checks it on each save: "Each update to the record increments the integer column lock_version and the locking facilities ensure that records instantiated twice will let the last one saved raise a StaleObjectError if the first was also updated."4 The application code does not call a lock.
References
- David Rice, Catalog of Patterns of Enterprise Application Architecture, Implicit Lock, pattern summary
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 16, Offline Concurrency Patterns, Implicit Lock
- Jakarta Persistence 3.2 specification, 3.5.1. Optimistic Locking
- Ruby on Rails API, ActiveRecord::Locking::Optimistic, Usage
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag XWFNBA Edit this page History Report an error Markdown