bossman
bossman

Reputation: 421

JPA difference between transaction isolation and entity locking

I have read about transaction isolation levels. It is used to prevent parallel transaction executions errors. Its quite obvious. There are also locking modes available for entities. I understand how they work.

But I cant find the reason why I need locking? I have used transaction isolation levels already. Why do I have to use locking? Do isolation levels and locking make the same job?

Upvotes: 13

Views: 4201

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154030

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:

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

  1. Explicit pessimistic lock modes:

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.

Upvotes: 13

V G
V G

Reputation: 19002

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.

Upvotes: 8

Related Questions