Search in sources :

Example 6 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project eclipselink by eclipse-ee4j.

the class EntityManagerImpl method find.

/**
 * Find by primary key.
 *
 * @param entityName
 *            - the entity class to find.
 * @param primaryKey
 *            - the entity primary key value, or primary key class, or a
 *            List of primary key values.
 * @return the found entity instance or null, if the entity does not exist.
 * @throws IllegalArgumentException
 *             if the first argument does not indicate an entity or if the
 *             second argument is not a valid type for that entity's
 *             primaryKey.
 */
public Object find(String entityName, Object primaryKey) {
    try {
        verifyOpen();
        AbstractSession session = (AbstractSession) getActiveSession();
        ClassDescriptor descriptor = session.getDescriptorForAlias(entityName);
        if (descriptor == null || descriptor.isDescriptorTypeAggregate()) {
            throw new IllegalArgumentException(ExceptionLocalization.buildMessage("unknown_entitybean_name", new Object[] { entityName }));
        }
        return findInternal(descriptor, session, primaryKey, null, null);
    } catch (LockTimeoutException e) {
        throw e;
    } catch (RuntimeException e) {
        setRollbackOnly();
        throw e;
    }
}
Also used : ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) LockTimeoutException(jakarta.persistence.LockTimeoutException) AbstractSession(org.eclipse.persistence.internal.sessions.AbstractSession)

Example 7 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project hibernate-orm by hibernate.

the class LockTest method testUpdateWithPessimisticReadLockWithoutNoWait.

@Test
@RequiresDialectFeature(value = DialectChecks.SupportsLockTimeouts.class)
public void testUpdateWithPessimisticReadLockWithoutNoWait() {
    Lock lock = new Lock();
    lock.setName("name");
    doInJPA(this::entityManagerFactory, entityManager -> {
        entityManager.persist(lock);
    });
    doInJPA(this::entityManagerFactory, _entityManager -> {
        _entityManager.find(Lock.class, lock.getId(), LockModeType.PESSIMISTIC_READ);
        AtomicBoolean failureExpected = new AtomicBoolean();
        try {
            doInJPA(this::entityManagerFactory, entityManager -> {
                try {
                    TransactionUtil.setJdbcTimeout(entityManager.unwrap(Session.class));
                    entityManager.createNativeQuery(updateStatement()).setParameter("name", "changed").setParameter("id", lock.getId()).executeUpdate();
                } catch (Exception e) {
                    if (ExceptionUtil.isSqlLockTimeout(e)) {
                        failureExpected.set(true);
                    }
                }
            });
        } catch (Exception e) {
            if (!failureExpected.get()) {
                fail("Should throw LockTimeoutException or PessimisticLockException");
            }
        }
    });
    doInJPA(this::entityManagerFactory, entityManager -> {
        Lock _lock = entityManager.merge(lock);
        entityManager.remove(_lock);
    });
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PessimisticLockException(jakarta.persistence.PessimisticLockException) PersistenceException(jakarta.persistence.PersistenceException) QueryTimeoutException(jakarta.persistence.QueryTimeoutException) TransactionException(org.hibernate.TransactionException) ExecutionException(java.util.concurrent.ExecutionException) LockTimeoutException(jakarta.persistence.LockTimeoutException) OptimisticLockException(jakarta.persistence.OptimisticLockException) Session(org.hibernate.Session) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature)

Example 8 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project hibernate-orm by hibernate.

the class LockTest method testContendedPessimisticReadLockTimeout.

@Test
@RequiresDialect(OracleDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testContendedPessimisticReadLockTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Lock lock = new Lock();
    FutureTask<Boolean> bgTask = new FutureTask<>(() -> {
        try {
            // true (success) if LockTimeoutException occurred
            AtomicBoolean timedOut = new AtomicBoolean();
            doInJPA(this::entityManagerFactory, _entityManager -> {
                log.info("testContendedPessimisticReadLockTimeout: (BG) about to read write-locked entity");
                // we should block on the following read
                Lock lock2 = _entityManager.getReference(Lock.class, lock.getId());
                // force entity to be read
                lock2.getName();
                log.info("testContendedPessimisticReadLockTimeout: (BG) read write-locked entity");
                Map<String, Object> props = new HashMap<String, Object>();
                // timeout is in milliseconds
                props.put(AvailableSettings.JPA_LOCK_TIMEOUT, 1000);
                try {
                    _entityManager.lock(lock2, LockModeType.PESSIMISTIC_READ, props);
                } catch (LockTimeoutException e) {
                    // success
                    log.info("testContendedPessimisticReadLockTimeout: (BG) got expected timeout exception");
                    timedOut.set(true);
                } catch (Throwable e) {
                    log.info("Expected LockTimeoutException but got unexpected exception", e);
                    throw new RuntimeException("Expected LockTimeoutException but got unexpected exception", e);
                }
            });
            return timedOut.get();
        } finally {
            // signal that we finished
            latch.countDown();
        }
    });
    Thread t = new Thread(bgTask);
    t.setDaemon(true);
    t.setName("Lock timeout Test (bg)");
    try {
        lock.setName("testContendedPessimisticReadLockTimeout");
        doInJPA(this::entityManagerFactory, em -> {
            em.persist(lock);
        });
        doInJPA(this::entityManagerFactory, em -> {
            Lock _lock = em.getReference(Lock.class, lock.getId());
            em.lock(_lock, LockModeType.PESSIMISTIC_WRITE);
            final Integer id = _lock.getId();
            // force entity to be read
            _lock.getName();
            log.info("testContendedPessimisticReadLockTimeout: got write lock");
            try {
                t.start();
                // should return quickly on success
                boolean latchSet = latch.await(20, TimeUnit.SECONDS);
                assertTrue("background test thread finished (lock timeout is broken)", latchSet);
                assertTrue("background test thread timed out on lock attempt", bgTask.get());
            } catch (InterruptedException e) {
                Thread.interrupted();
            } catch (ExecutionException e) {
                throw new AssertionError(e);
            }
        });
    } finally {
        awaitThenDelete("testContendedPessimisticReadLockTimeout", t, lock.getId());
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FutureTask(java.util.concurrent.FutureTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionException(java.util.concurrent.ExecutionException) LockTimeoutException(jakarta.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 9 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project hibernate-orm by hibernate.

the class LockTest method testLockTimeoutEMProps.

@Test
@RequiresDialect(OracleDialect.class)
@RequiresDialectFeature(DialectChecks.SupportsLockTimeouts.class)
public void testLockTimeoutEMProps() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Map<String, Object> timeoutProps = new HashMap<String, Object>();
    // 1 second timeout
    timeoutProps.put(AvailableSettings.JPA_LOCK_TIMEOUT, 1000);
    final Lock lock = new Lock();
    FutureTask<Boolean> bgTask = new FutureTask<>(() -> {
        try {
            // true (success) if LockTimeoutException occurred
            AtomicBoolean timedOut = new AtomicBoolean();
            doInJPA(this::entityManagerFactory, _entityManager -> {
                log.info("testLockTimeoutEMProps: (BG) about to read write-locked entity");
                // we should block on the following read
                Lock lock2 = _entityManager.getReference(Lock.class, lock.getId());
                // force entity to be read
                lock2.getName();
                log.info("testLockTimeoutEMProps: (BG) read write-locked entity");
                // em2 already has AvailableSettings.LOCK_TIMEOUT of 1 second applied
                try {
                    _entityManager.lock(lock2, LockModeType.PESSIMISTIC_WRITE);
                } catch (LockTimeoutException e) {
                    // success
                    log.info("testLockTimeoutEMProps: (BG) got expected timeout exception");
                    timedOut.set(true);
                } catch (Throwable e) {
                    log.info("Expected LockTimeoutException but got unexpected exception", e);
                }
            }, timeoutProps);
            return timedOut.get();
        } finally {
            // signal that we finished
            latch.countDown();
        }
    });
    Thread t = new Thread(bgTask);
    t.setDaemon(true);
    t.setName("Lock timeout Test (bg)");
    try {
        lock.setName("testLockTimeoutEMProps");
        doInJPA(this::entityManagerFactory, em -> {
            em.persist(lock);
        });
        doInJPA(this::entityManagerFactory, em -> {
            Lock _lock = em.getReference(Lock.class, lock.getId());
            em.lock(_lock, LockModeType.PESSIMISTIC_WRITE);
            final Integer id = _lock.getId();
            // force entity to be read
            _lock.getName();
            log.info("testLockTimeoutEMProps: got write lock");
            try {
                t.start();
                // should return quickly on success
                boolean latchSet = latch.await(20, TimeUnit.SECONDS);
                assertTrue("background test thread finished (lock timeout is broken)", latchSet);
                assertTrue("background test thread timed out on lock attempt", bgTask.get());
            } catch (InterruptedException e) {
                Thread.interrupted();
            } catch (ExecutionException e) {
                throw new AssertionError(e);
            }
        });
    } finally {
        awaitThenDelete("testLockTimeoutEMProps", t, lock.getId());
    }
}
Also used : HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FutureTask(java.util.concurrent.FutureTask) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ExecutionException(java.util.concurrent.ExecutionException) LockTimeoutException(jakarta.persistence.LockTimeoutException) Test(org.junit.Test) RequiresDialectFeature(org.hibernate.testing.RequiresDialectFeature) RequiresDialect(org.hibernate.testing.RequiresDialect)

Example 10 with LockTimeoutException

use of jakarta.persistence.LockTimeoutException in project hibernate-orm by hibernate.

the class LockExceptionTests method testLockTimeoutRefresh.

@Test
public void testLockTimeoutRefresh() {
    final Item item = new Item("refresh");
    inTransaction(session -> session.persist(item));
    try {
        inTransaction(session -> {
            session.find(Item.class, item.getId(), LockModeType.PESSIMISTIC_WRITE);
            TransactionUtil2.inTransaction(sessionFactory(), secondSession -> {
                try {
                    // generally speaking we should be able to read the row
                    Item item2 = secondSession.get(Item.class, item.getId());
                    secondSession.refresh(item2, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap(AvailableSettings.JAKARTA_LOCK_TIMEOUT, LockOptions.NO_WAIT));
                    fail("Expecting a failure");
                } catch (LockTimeoutException | PessimisticLockException expected) {
                // expected outcome
                }
            });
        });
    } finally {
        inTransaction(session -> session.createQuery("delete Item").executeUpdate());
    }
}
Also used : Item(org.hibernate.orm.test.jpa.model.Item) LockTimeoutException(jakarta.persistence.LockTimeoutException) PessimisticLockException(jakarta.persistence.PessimisticLockException) AbstractJPATest(org.hibernate.orm.test.jpa.model.AbstractJPATest) Test(org.junit.jupiter.api.Test)

Aggregations

LockTimeoutException (jakarta.persistence.LockTimeoutException)20 PersistenceException (jakarta.persistence.PersistenceException)10 PessimisticLockException (jakarta.persistence.PessimisticLockException)5 List (java.util.List)5 ExecutionException (java.util.concurrent.ExecutionException)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 RequiresDialectFeature (org.hibernate.testing.RequiresDialectFeature)5 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 FutureTask (java.util.concurrent.FutureTask)4 RequiresDialect (org.hibernate.testing.RequiresDialect)4 QueryTimeoutException (jakarta.persistence.QueryTimeoutException)3 ArrayList (java.util.ArrayList)3 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)3 ReadObjectQuery (org.eclipse.persistence.queries.ReadObjectQuery)3 AbstractJPATest (org.hibernate.orm.test.jpa.model.AbstractJPATest)3 Item (org.hibernate.orm.test.jpa.model.Item)3 Test (org.junit.jupiter.api.Test)3 OptimisticLockException (jakarta.persistence.OptimisticLockException)2