Optimistic Locking Implementation in Java
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 in Java: what you actually reach for
Java implementation
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 FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
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).
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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.