Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Optimistic Locking Implementation in Java

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Optimistic Locking runs in O(1) time and O(1) space, in Java as in every other language.
  • ✓JPA does this declaratively: jakarta.persistence.Version on a long field makes Hibernate append AND version = ?
  • ✓The version field is a primitive long and is never assigned by application code; a reviewer will flag any setter for it.
  • ✓The Java trap: Type the version as Long instead of long and equality silently changes meaning: Long.valueOf caches minus 128 through 127, so v1 == v2 holds for every version a test ever produces and starts failing in production once a row has been updated 128 times.
  • ✓The version predicate is free; the JVM costs sit elsewhere. A contended AtomicLong compare-and-set loop ping-pongs one cacheline between cores and degrades superlinearly, which is why LongAdder trades a more expensive sum for striped writes and wins past a few threads.

What Optimistic Locking actually is

Optimistic locking never takes a lock. You read a record together with a version token (an integer, a timestamp, a SQL Server rowversion, an HTTP ETag), mutate a private copy, then write back with the token in the predicate: UPDATE ... SET v = v + 1 WHERE id = ? AND v = ?. If the affected-row count comes back zero, somebody else wrote first, so you discard your work and retry from a fresh read. The whole design is a bet that conflicts are rare, and the cost of losing the bet is a wasted round trip rather than a stalled thread. That is the opposite trade from mutual exclusion, which pays coordination cost on every access so conflicts become impossible. Two hazards are permanent. The retry loop must be bounded and jittered or contention becomes livelock. And a token that can be reused makes equality a lie: the value went A, then B, then back to A, your check passes, and a change you never observed is silently overwritten. The eight languages diverge because the token lives somewhere different in each. Some hand you a declarative version column in the ORM, some make you count rows off the driver yourself, and in shared memory the primitive is a hardware compare-and-swap whose exact signature, memory ordering rules and spurious-failure behaviour are genuinely different per language.

Optimistic Locking in Java: what you actually reach for

JPA does this declaratively: jakarta.persistence.Version on a long field makes Hibernate append AND version = ? to every UPDATE, bump the column, and throw OptimisticLockException, which Spring rethrows as org.springframework.orm.ObjectOptimisticLockingFailureException. EntityManager.lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT) bumps a parent whose children changed. In memory java.util.concurrent.atomic covers the rest: AtomicReference.compareAndSet, updateAndGet which hides the loop entirely, LongAdder for contended counters, and AtomicStampedReference, the only class in any of these standard libraries built specifically to defeat token reuse by pairing the reference with a stamp.

Java implementation

The version field is a primitive long and is never assigned by application code; a reviewer will flag any setter for it. Retries live outside the transaction boundary, because the check only happens at flush time. updateAndGet or accumulateAndGet is preferred to a hand-written compareAndSet loop. Detached entities returning from a client must carry their version so the merge can detect the conflict; dropping the token and re-reading the row quietly converts optimistic locking into last-write-wins, which is the failure mode the whole design exists to prevent.
java
import jakarta.persistence.*;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.transaction.annotation.*;

@Entity
class Account {
  @Id Long id;
  long balance;
  @Version long version;  // primitive: a boxed Long would compare by identity
}                         // past the -128..127 valueOf cache

@Service
class TxOps {
  @PersistenceContext EntityManager em;

  // Hibernate only emits "UPDATE ... AND version = ?" at flush, i.e. at COMMIT,
  // which happens after this method returns -- a try/catch in here can never
  // observe the conflict.
  @Transactional(propagation = Propagation.REQUIRES_NEW)
  void withdrawOnce(long id, long amt) {
    Account a = em.find(Account.class, id);
    if (a.balance < amt) throw new IllegalArgumentException("insufficient");
    a.balance -= amt;   // never touch a.version; Hibernate owns it
  }
}

@Service
class Accounts {
  private final TxOps tx;                // separate bean on purpose:
  Accounts(TxOps tx) { this.tx = tx; }   // self-invocation bypasses the proxy

  void withdraw(long id, long amt) throws InterruptedException {
    for (int i = 0; i < 5; i++) {
      try { tx.withdrawOnce(id, amt); return; }
      catch (OptimisticLockException | ObjectOptimisticLockingFailureException e) {
        Thread.sleep(5L << i);           // cheap on a virtual thread (21+)
      }
    }
    throw new IllegalStateException("conflict budget exhausted");
  }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Java-specific trap

Type the version as Long instead of long and equality silently changes meaning: Long.valueOf caches minus 128 through 127, so v1 == v2 holds for every version a test ever produces and starts failing in production once a row has been updated 128 times. Use the primitive, or equals. The larger structural trap is when the check fires. Hibernate emits the versioned UPDATE at flush, which for a container-managed transaction means at commit, after your method has already returned. A try/catch around the repository call inside the same transactional method therefore never sees OptimisticLockException, and retrying there reuses a persistence context that is already doomed. The retry must wrap the entire transaction from outside.

Performance in Java, beyond the O(1)

The version predicate is free; the JVM costs sit elsewhere. A contended AtomicLong compare-and-set loop ping-pongs one cacheline between cores and degrades superlinearly, which is why LongAdder trades a more expensive sum for striped writes and wins past a few threads. A non-volatile field read inside a retry loop can be hoisted out by the JIT into an infinite loop, and the volatile semantics baked into the Atomic classes are what prevent it. Autoboxing a Long version allocates unless escape analysis scalar-replaces it. Virtual threads from 21 make a blocking backoff cost a heap frame instead of an OS thread. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Optimistic Locking between languages.

Real-World Applications

Optimistic Locking is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Optimistic Locking helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Optimistic Locking appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Optimistic Locking over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Optimistic Locking to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for Optimistic Locking?

JPA does this declaratively: jakarta.persistence.Version on a long field makes Hibernate append AND version = ? to every UPDATE, bump the column, and throw OptimisticLockException, which Spring rethrows as org.springframework.orm.ObjectOptimisticLockingFailureException. EntityManager.lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT) bumps a parent whose children changed. In memory java.util.concurrent.atomic covers the rest: AtomicReference.compareAndSet, updateAndGet which hides the loop entirely, LongAdder for contended counters, and AtomicStampedReference, the only class in any of these standard libraries built specifically to defeat token reuse by pairing the reference with a stamp.

What is the most common Java mistake when implementing Optimistic Locking?

Type the version as Long instead of long and equality silently changes meaning: Long.valueOf caches minus 128 through 127, so v1 == v2 holds for every version a test ever produces and starts failing in production once a row has been updated 128 times. Use the primitive, or equals. The larger structural trap is when the check fires. Hibernate emits the versioned UPDATE at flush, which for a container-managed transaction means at commit, after your method has already returned. A try/catch around the repository call inside the same transactional method therefore never sees OptimisticLockException, and retrying there reuses a persistence context that is already doomed. The retry must wrap the entire transaction from outside.

How does Optimistic Locking actually perform in Java?

The version predicate is free; the JVM costs sit elsewhere. A contended AtomicLong compare-and-set loop ping-pongs one cacheline between cores and degrades superlinearly, which is why LongAdder trades a more expensive sum for striped writes and wins past a few threads. A non-volatile field read inside a retry loop can be hoisted out by the JIT into an infinite loop, and the volatile semantics baked into the Atomic classes are what prevent it. Autoboxing a Long version allocates unless escape analysis scalar-replaces it. Virtual threads from 21 make a blocking backoff cost a heap frame instead of an OS thread. Time complexity is O(1) and space is O(1).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.