Optimistic locking
What you will learn
Use version checks or explicit locks to prevent conflicting updates; choose transaction boundaries that protect the invariant.
- Explain lost updates and @Version.
- Distinguish optimistic and pessimistic locking.
- Handle conflict and rollback in a new transaction.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. JPA examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Version check model
public class Main { record Snapshot(int stock,int version) {} static class Row { int stock,version; Row(int s,int v){stock=s;version=v;} synchronized Snapshot snapshot(){return new Snapshot(stock,version);} synchronized boolean write(int expected,int next){if(next<0)throw new IllegalArgumentException(); if(version!=expected)return false; stock=next;version++;return true;} } public static void main(String[] args) {var row=new Row(5,0); var a=row.snapshot(); var b=row.snapshot();System.out.println(row.write(a.version(),3)); System.out.println(row.write(b.version(),4));System.out.println(row.snapshot()); }}Expected output:
truefalseSnapshot[stock=3, version=1]A synchronized in-memory compare-and-set model illustrates stale writes. It does not implement database isolation.
Optimistic versioning
Two transactions may read the same row version. An update of a versioned entity checks the previous version and advances it; a stale writer fails rather than silently overwriting. A representative SQL shape is UPDATE product SET stock=?, version=? WHERE id=? AND version=?; the provider controls actual SQL. OptimisticLockException may arise at merge, flush or commit, and marks the active transaction for rollback. Spring may translate it into an optimistic locking data-access exception. Never manually increment or accept the entity version as a mutable client field. If retries are appropriate, reread and revalidate in a new transaction, bound retry count, and avoid repeating external side effects. Bulk JPQL updates bypass normal managed-entity dirty checking and optimistic checks unless explicitly designed; clear or refresh affected contexts.
Pessimistic locking and transaction integration
A PESSIMISTIC_WRITE query requests a database lock on selected data within an active transaction, potentially blocking or failing; it is not a JVM synchronized block. Lock scope and timeouts depend on the database/provider. Keep transactions short, order locks consistently and handle failures. Constraints protect invariants even across application instances; check stock in the service and enforce nonnegative stock in SQL. The companion test uses two independent contexts reading one row, commits the first update, then expects the second flush to fail. It also checks rollback after successful flush. Actual PostgreSQL isolation, lock timeouts and generated SQL remain unverified.
Revalidate a reservation
public class Main {
public static void main(String[] args) {int stock=3; int requested=4;try { if(requested<=0 || requested>stock) throw new IllegalArgumentException(); stock-=requested; }catch(IllegalArgumentException e){System.out.println("rejected");}System.out.println(stock); }}Expected output:
rejected3After rereading stock, the original command can become invalid; do not retry blindly.
Transaction and version integration test
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/test/java/example/catalog/PersistenceTest.java; use the companion lab README.
package example.catalog;import jakarta.persistence.*;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.beans.factory.annotation.Autowired;import org.hibernate.SessionFactory;import static org.junit.jupiter.api.Assertions.*;@SpringBootTestclass PersistenceTest { @Autowired EntityManagerFactory factory; @Test void catalogLifecycleAndConflict() { // Fresh dedicated database; unique fixture names for each invocation. String suffix = java.util.UUID.randomUUID().toString().replace("-", "").substring(0,8).toUpperCase(java.util.Locale.ROOT); Long id; try (EntityManager em = factory.createEntityManager()) { em.getTransaction().begin(); Category c = new Category("Stationery-" + suffix); Product p = c.add("A" + suffix, 5); em.persist(c); em.persist(p); em.getTransaction().commit(); id = p.getId(); } try (EntityManager em = factory.createEntityManager()) { em.getTransaction().begin(); ContextWalk.demonstrate(em,id); em.getTransaction().rollback(); } try (EntityManager a = factory.createEntityManager(); EntityManager b = factory.createEntityManager()) { a.getTransaction().begin(); b.getTransaction().begin(); Product first = a.find(Product.class,id); Product stale = b.find(Product.class,id); first.reserve(2); a.getTransaction().commit(); stale.reserve(1); try { assertThrows(OptimisticLockException.class, b::flush); } finally { if (b.getTransaction().isActive()) b.getTransaction().rollback(); } } try (EntityManager em = factory.createEntityManager()) { em.getTransaction().begin(); assertEquals(3, em.find(Product.class,id).getStock()); em.find(Product.class,id).reserve(1); em.flush(); em.getTransaction().rollback(); } try (EntityManager em = factory.createEntityManager()) { assertEquals(3, em.find(Product.class,id).getStock()); } // Separate fresh context; record actual SQL separately when running this lab. var stats = factory.unwrap(SessionFactory.class).getStatistics(); stats.clear(); try (EntityManager em = factory.createEntityManager()) { var p = em.createQuery("select p from Product p join fetch p.category where p.id = :id",Product.class) .setParameter("id",id).getSingleResult(); assertTrue(p.getCategory().getName().startsWith("Stationery-")); assertEquals(1L, stats.getPrepareStatementCount()); } }}Predicted behavior: A stale version fails; rollback restores stock; fresh fetch join checks one statement.
Run only in the disposable PostgreSQL lab; no test result is claimed.
Database constraints
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/schema.sql; use the companion lab README.
-- Run once only against a fresh, disposable PostgreSQL 17 database.CREATE TABLE category (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name varchar(80) NOT NULL UNIQUE);CREATE TABLE product (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, sku varchar(12) NOT NULL UNIQUE, stock integer NOT NULL CHECK (stock >= 0), version bigint NOT NULL, category_id bigint NOT NULL REFERENCES category(id));CREATE INDEX product_category_idx ON product(category_id);Predicted behavior: Primary keys, unique SKU, foreign key and nonnegative stock constraints.
Apply once in a new disposable database; schema validation does not test all constraints.
Common mistakes
Do not catch a stale-version exception then continue the same transaction, assume a JVM monitor protects distributed writers, or use unbounded retries.
Practice
Simulate two snapshots of stock 8 and version 0, write stock 6 using the first, reject the stale second; print stock and version.
Expected output:
truefalseSnapshot[stock=6, version=1]Compare with the manual review criteria.
Official reading: Spec · Locking · Transactions. ORM execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Optimistic locking — knowledge check
JPA mapping and persistence reasoning.
What does @Version help detect?
When may an optimistic lock failure appear?
What should a retry use?
What does PESSIMISTIC_WRITE request?
Why add a SQL stock constraint?