JPA difference between transaction isolation and entity locking

Both transaction isolation and JPA Entity locking are concurrency control mechanisms.

The transaction isolation is applied on a JDBC Connection level and the scope is the transaction life-cycle itself (you can't change the transaction isolation from your current running transactions). Modern databases allow you to use both 2PL (two-phase locking) isolation levels and MVCC ones (SNAPSHOT_ISOLATION or PostgreSQL isolation levels). In MVCC, readers do not block writers and writers do not block readers (only writers block writers).

The Java Persistence Locking API offers both database-level and application-level concurrency control, which can be split in two categories:

  1. Explicit Optimistic lock modes:

    • OPTIMISTIC
    • OPTIMISTIC_FORCE_INCREMENT
    • PESSIMISTIC_FORCE_INCREMENT

The optimistic locking uses version checks in UPDATE/DELETE statements and fail on version mismatches.

  1. Explicit pessimistic lock modes:

    • PESSIMISTIC_READ
    • PESSIMISTIC_WRITE

The pessimistic lock modes use a database-specific lock syntax to acquire read (shared) or write (exclusive) locks (eg. SELECT ... FOR UPDATE).

An explicit lock mode is suitable when you run on a lower-consistency isolation level (READ_COMMITTED) and you want to acquire locks whose scope are upgraded from query life-time to a transaction life-time.


Introduction

There are different locking types and isolation levels. Some of the locking types (OPTIMISTIC*) are implemented on the JPA-level (eg. in EclipseLink or Hibernate), and other (PESSIMISTIC*) are delegated by the JPA-provider to the DB level.

Explanation

Isolation levels and locking are not the same, but they may intersect somewhere. If you have the SERIALIZED isolation level (which is performance-greedy), then you do not need any locking to do in JPA, as it is already done by the DB. On the other side, if you choose READ_COMMITTED, then you may need to make some locking, as the isolation level alone will not guarantee you e.g that the entry is not changed in the meanwhile by another transaction.