Search in sources :

Example 1 with LockAcquisitionException

use of org.hibernate.exception.LockAcquisitionException in project hibernate-orm by hibernate.

the class SQLStateConversionDelegate method convert.

@Override
public JDBCException convert(SQLException sqlException, String message, String sql) {
    final String sqlState = JdbcExceptionHelper.extractSqlState(sqlException);
    final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
    if (sqlState != null) {
        String sqlStateClassCode = JdbcExceptionHelper.determineSqlStateClassCode(sqlState);
        if (sqlStateClassCode != null) {
            if (SQL_GRAMMAR_CATEGORIES.contains(sqlStateClassCode)) {
                return new SQLGrammarException(message, sqlException, sql);
            } else if (INTEGRITY_VIOLATION_CATEGORIES.contains(sqlStateClassCode)) {
                final String constraintName = getConversionContext().getViolatedConstraintNameExtracter().extractConstraintName(sqlException);
                return new ConstraintViolationException(message, sqlException, sql, constraintName);
            } else if (CONNECTION_CATEGORIES.contains(sqlStateClassCode)) {
                return new JDBCConnectionException(message, sqlException, sql);
            } else if (DATA_CATEGORIES.contains(sqlStateClassCode)) {
                return new DataException(message, sqlException, sql);
            }
        }
        if ("40001".equals(sqlState)) {
            return new LockAcquisitionException(message, sqlException, sql);
        }
        if ("40XL1".equals(sqlState) || "40XL2".equals(sqlState)) {
            // Derby "A lock could not be obtained within the time requested."
            return new PessimisticLockException(message, sqlException, sql);
        }
        // MySQL Query execution was interrupted
        if ("70100".equals(sqlState) || // Oracle user requested cancel of current operation
        ("72000".equals(sqlState) && errorCode == 1013)) {
            throw new QueryTimeoutException(message, sqlException, sql);
        }
    }
    return null;
}
Also used : DataException(org.hibernate.exception.DataException) QueryTimeoutException(org.hibernate.QueryTimeoutException) JDBCConnectionException(org.hibernate.exception.JDBCConnectionException) SQLGrammarException(org.hibernate.exception.SQLGrammarException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) PessimisticLockException(org.hibernate.PessimisticLockException)

Example 2 with LockAcquisitionException

use of org.hibernate.exception.LockAcquisitionException in project stdlib by petergeneric.

the class TransactionMethodInterceptor method invoke.

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    if (sessionProvider.get().getTransaction().getStatus() == TransactionStatus.ACTIVE) {
        // allow silent joining of enclosing transactional methods (NOTE: this ignores the current method's txn-al settings)
        if (log.isTraceEnabled())
            log.trace("Joining existing transaction to call " + invocation.getMethod().toGenericString());
        return invocation.proceed();
    } else {
        Timer.Context callTimer = calls.time();
        final String tracingId = Tracing.log("TX:begin", () -> invocation.getMethod().toGenericString());
        try {
            final Transactional annotation = readAnnotation(invocation);
            // After the max attempts for auto retry are exhausted we'll fall back on the non-retrying default behaviour
            if (annotation.autoRetry()) {
                // Try all but the last attempt
                final int retries = Math.max(0, annotation.autoRetryCount() - 1);
                // N.B. more aggressive than the @Retry annotation implements
                long backoff = 1000;
                final double multiplier = 1.5;
                for (int attempt = 0; attempt < retries; attempt++) {
                    try {
                        return createTransactionAndExecuteMethod(invocation, annotation);
                    } catch (LockAcquisitionException | StaleStateException | GenericJDBCException | OptimisticLockException e) {
                        if (log.isTraceEnabled())
                            log.warn("@Transactional caught exception " + e.getClass().getSimpleName() + "; retrying...", e);
                        else
                            log.warn("@Transactional caught exception " + e.getClass().getSimpleName() + "; retrying...");
                        Tracing.logOngoing(tracingId, "TX:exception:retryable", () -> e.getClass().getSimpleName());
                        try {
                            Thread.sleep(backoff);
                        } catch (InterruptedException ie) {
                            throw new RuntimeException("Interrupted while attempting a @Transactional retry!", ie);
                        }
                        // Increase backoff for the next exception
                        backoff *= multiplier;
                    } catch (PersistenceException e) {
                        // Handle generic exception (usually one that wraps another exception)
                        if (e.getCause() != null && (isSqlServerSnapshotConflictError(e) || isDeadlockError(e))) {
                            if (log.isTraceEnabled())
                                log.warn("@Transactional caught exception PersistenceException wrapping " + e.getCause().getClass().getSimpleName() + "; retrying...", e);
                            else
                                log.warn("@Transactional caught exception PersistenceException wrapping " + e.getCause().getClass().getSimpleName() + "; retrying...");
                            Tracing.logOngoing(tracingId, "TX:exception:retryable:wrapped", () -> e.getCause().getClass().getSimpleName());
                            try {
                                Thread.sleep(backoff);
                            } catch (InterruptedException ie) {
                                throw new RuntimeException("Interrupted while attempting a @Transactional retry!", ie);
                            }
                            // Increase backoff for the next exception
                            backoff *= multiplier;
                        } else {
                            Tracing.logOngoing(tracingId, "TX:exception:fatal", () -> e.getClass().getSimpleName());
                            // rethrow because we won't handle this
                            throw e;
                        }
                    }
                }
            }
            Tracing.logOngoing(tracingId, "TX:last-try", null);
            // Run without further retries
            return createTransactionAndExecuteMethod(invocation, annotation);
        } finally {
            Tracing.logOngoing(tracingId, "TX:quit", null);
            callTimer.stop();
        }
    }
}
Also used : OptimisticLockException(javax.persistence.OptimisticLockException) Timer(com.codahale.metrics.Timer) StaleStateException(org.hibernate.StaleStateException) PersistenceException(javax.persistence.PersistenceException) GenericJDBCException(org.hibernate.exception.GenericJDBCException) Transactional(com.peterphi.std.guice.database.annotation.Transactional) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException)

Example 3 with LockAcquisitionException

use of org.hibernate.exception.LockAcquisitionException in project kylo by Teradata.

the class ProvenanceEventReceiver method processEvent.

/**
 * process the event and persist it along with creating the Job and Step.  If there is a lock error it will retry until it hits the {@link #lockAcquisitionRetryAmount}
 *
 * @param event        a provenance event
 * @param retryAttempt the retry number.  If there is a lock error it will retry until it hits the {@link #lockAcquisitionRetryAmount}
 */
private void processEvent(ProvenanceEventRecordDTO event, int retryAttempt) {
    try {
        OpsManagerFeed feed = provenanceEventFeedUtil.getFeed(event);
        log.debug("Process {} for flowfile: {} and processorId: {} ", event, event.getJobFlowFileId(), event.getFirstEventProcessorId());
        // ensure the job is there
        BatchJobExecution jobExecution = findOrCreateJobExecution(event, feed);
        if (jobExecution != null) {
            batchJobExecutionProvider.updateFeedJobStartTime(jobExecution, feed);
        }
        if (jobExecution != null && !event.isStream()) {
            metadataAccess.commit(() -> receiveBatchEvent(jobExecution, event), MetadataAccess.SERVICE);
        }
        if (jobExecution != null && event.isFinalJobEvent()) {
            notifyJobFinished(jobExecution, event);
        }
    } catch (LockAcquisitionException lae) {
        if (retryAttempt < lockAcquisitionRetryAmount) {
            retryAttempt++;
            log.error("LockAcquisitionException found trying to process Event: {} .  Retry attempt # {} ", event, retryAttempt, lae);
            // wait and re attempt
            try {
                Thread.sleep(300L);
            } catch (InterruptedException var10) {
            }
            processEvent(event, retryAttempt);
        } else {
            log.error("LockAcquisitionException found.  Unsuccessful after retrying {} times.  This event {} will not be processed. ", retryAttempt, event, lae);
        }
    } catch (Exception e) {
        log.error("Error processing Event ", event, e);
    }
}
Also used : OpsManagerFeed(com.thinkbiganalytics.metadata.api.feed.OpsManagerFeed) BatchJobExecution(com.thinkbiganalytics.metadata.api.jobrepo.job.BatchJobExecution) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException)

Example 4 with LockAcquisitionException

use of org.hibernate.exception.LockAcquisitionException in project hibernate-orm by hibernate.

the class PostgreSQL81DialectTestCase method testDeadlockException.

@Test
public void testDeadlockException() {
    PostgreSQL81Dialect dialect = new PostgreSQL81Dialect();
    SQLExceptionConversionDelegate delegate = dialect.buildSQLExceptionConversionDelegate();
    assertNotNull(delegate);
    JDBCException exception = delegate.convert(new SQLException("Deadlock Detected", "40P01"), "", "");
    assertTrue(exception instanceof LockAcquisitionException);
}
Also used : SQLExceptionConversionDelegate(org.hibernate.exception.spi.SQLExceptionConversionDelegate) JDBCException(org.hibernate.JDBCException) SQLException(java.sql.SQLException) LockAcquisitionException(org.hibernate.exception.LockAcquisitionException) Test(org.junit.Test)

Aggregations

LockAcquisitionException (org.hibernate.exception.LockAcquisitionException)4 Timer (com.codahale.metrics.Timer)1 Transactional (com.peterphi.std.guice.database.annotation.Transactional)1 OpsManagerFeed (com.thinkbiganalytics.metadata.api.feed.OpsManagerFeed)1 BatchJobExecution (com.thinkbiganalytics.metadata.api.jobrepo.job.BatchJobExecution)1 SQLException (java.sql.SQLException)1 OptimisticLockException (javax.persistence.OptimisticLockException)1 PersistenceException (javax.persistence.PersistenceException)1 JDBCException (org.hibernate.JDBCException)1 PessimisticLockException (org.hibernate.PessimisticLockException)1 QueryTimeoutException (org.hibernate.QueryTimeoutException)1 StaleStateException (org.hibernate.StaleStateException)1 ConstraintViolationException (org.hibernate.exception.ConstraintViolationException)1 DataException (org.hibernate.exception.DataException)1 GenericJDBCException (org.hibernate.exception.GenericJDBCException)1 JDBCConnectionException (org.hibernate.exception.JDBCConnectionException)1 SQLGrammarException (org.hibernate.exception.SQLGrammarException)1 SQLExceptionConversionDelegate (org.hibernate.exception.spi.SQLExceptionConversionDelegate)1 Test (org.junit.Test)1