Skip to main content

JPA 2.0 Concurrency and locking

Posted by caroljmcdonald on July 30, 2009 at 2:39 PM PDT


Optimistic Concurrency

Optimistic locking lets concurrent transactions process simultaneously,
but detects and prevent collisions, this works best for applications
where most concurrent transactions do not conflict. JPA Optimistic
locking allows anyone to read and update an entity, however a version
check is made upon commit and an exception is thrown if the version was
updated in the database since the entity was read.  In JPA for
Optimistic locking you annotate an attribute with @Version as shown

public class Employee {

    @ID int id;

    @Version int version;

The Version attribute will be incremented with a successful commit. The
Version attribute can be an int, short, long, or timestamp.  This
results in SQL like the following:


JPA 2.0 Concurrency and

Hello Carol,
I'm trying to make some points on JPA concurrency clear to me. Thanks, for the article you wrote and the presentation.
I have a question about optimistic locking.
In the "OPTIMISTIC_FORCE_INCREMENT (write) LockMode Example" section of this arcticle in the example of the tx2 there is an explicit call to em.flush() used.
You write that this causes version to updated in the DB, however I never get this field updated in the DB just after em.flush() called, only after tx.commit().
If I call em.flush() in the tx2 before tx1 get commited, tx1 fails to commit. Moreover it seems tx1 get blocked waiting for tx2 (I use OpenJPA 2.0). However without em.flush() the first transaction commits successfully.
Could you clarify when shall I use explicit em.flush() call in a context of JPA locking ?

JPA 2.0 Concurrency and

I tried your second example with hibernate (OPTIMISTIC (READ) LockMode Example)

This does not works. Hibernate seems to ignire the modified (in first txn) dep field as unchanged in the second txn.

Hibernate does not fire any selects to verify the status of dep entity. Probably because it is unchanged, hibernate ignores it.