EntityTransaction.commit() does not release a pessimistic lock


It appears that EntityTransaction.commit() does not release a pessimistic lock -> test code below.

I tried it in with the current (2.7.6_01) and older versions (2.6.9, 2.5.7, 2.4.7) with the same result.

(side note: EntityTransaction.rollback() releases it correctly)

// Account.java

package icke;
import javax.persistence.Entity;
import javax.persistence.Id;

public class Account {
  private int no;
  private int balance;
  public Account(int n) {
    no = n;
    balance = 1000;
  public int getNo() {
    return no;
  public int getBalance() {
    return balance;
  public void credit(int a) {
    balance += a;

// Main.java

package icke;
import javax.persistence.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) {
    try {
    catch (Exception e) {
  public static void testLocking() {
    // persist
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("accounts.odb");
    EntityManager em = emf.createEntityManager();
    em.persist(new Account(0));
    // update
    EntityManager em1 = emf.createEntityManager();
    Account a1 = em1.find(Account.class, 0, LockModeType.PESSIMISTIC_WRITE);
    System.out.println(em1.getLockMode(a1)); // -> PESSIMISTIC_WRITE
    // try to retrieve again
    EntityManager em2 = emf.createEntityManager();
    Account a2 = em2.find(Account.class, 0, LockModeType.PESSIMISTIC_READ); // -> LockTimeoutException

You are right. Pessimistic locks are not released automatically (by default) on transaction commit. The reason is that entity objects are still in managed status with valid values after commit and the application can still use them for further processing and update. Locks are released automatically when the EntityManager is closed.

In JDO you can change the default using setDetachAllOnCommit. You can also use this JDO feature from JPA when you use ObjectDB. Giving an EntityManager em:

        PersistenceManager pm  = em.unwrap(PersistenceManager.class);

In this case entity objects will be detached and unlocked on transaction commit.

ObjectDB Support