Home » Java » spring – JPA EntityManager.lock with H2 DB – java.sql.SQLException: Connection is closed when multiple Transactions use lock on same entity-Exceptionshub

spring – JPA EntityManager.lock with H2 DB – java.sql.SQLException: Connection is closed when multiple Transactions use lock on same entity-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am implementing application where data blobs are downloaded. I want to make sure that when two download Transactions start around the same time, the first Transaction locks the data and I don’t want the second download to proceed (only first one should get the data)

Using JPA EntityManager, H2 database

My Code in question:

    @Transactional
    public void foobar() throws PessimisticLockException{

        log.debug("Thread " + Thread.currentThread().getName() + " Trying to lock");
        entityManager.lock(nachricht, LockModeType.PESSIMISTIC_WRITE);
        entityManager.refresh(nachricht);
        log.debug("Thread " + Thread.currentThread().getName() + " unlocked");
        log.debug("Thread " + Thread.currentThread().getName() + " Löschdatun: " + nachricht.getLoeschDatum());
        log.debug("Thread " + Thread.currentThread().getName() + " start download");

        // Thread sleep so I can better debug multiple transactions at the same time
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        // My code etc etc etc

        log.debug("Thread " + Thread.currentThread().getName() + " end download");

    }

Here is my StackTrace of what I don’t understand:

2020-02-19 10:17:33.447  WARN 15652 --- [         task-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 50200, SQLState: HYT00
2020-02-19 10:17:33.447 ERROR 15652 --- [         task-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Zeitüberschreitung beim Versuch die Tabelle {0} zu sperren
Timeout trying to lock table {0}; SQL statement:
select id from nachricht where id =? for update [50200-200]
2020-02-19 10:17:33.454 ERROR 15652 --- [         task-6] o.s.t.i.TransactionInterceptor           : Application exception overridden by rollback exception
javax.persistence.PessimisticLockException: could not obtain pessimistic lock
at org.hibernate.internal.ExceptionConverterImpl.wrapLockException(ExceptionConverterImpl.java:262) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:103) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:200) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.lock(SessionImpl.java:3436) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.lock(SessionImpl.java:3419) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:368) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy169.lock(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at com.sun.proxy.$Proxy169.lock(Unknown Source) ~[na:na]
at de.lyth.compertis.kundenportal.repository.DownloadService.downloadNachricht(DownloadService.java:49) ~[main/:na]
at de.lyth.compertis.kundenportal.repository.DownloadService$$FastClassBySpringCGLIB$$adbb5636.invoke(<generated>) ~[main/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at de.lyth.compertis.kundenportal.repository.DownloadService$$EnhancerBySpringCGLIB$$a19d9494.downloadNachricht(<generated>) ~[main/:na]
at de.lyth.compertis.kundenportal.api.KundeController$1.writeTo(KundeController.java:312) ~[main/:na]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:111) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:98) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$4(WebAsyncManager.java:328) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
Caused by: org.hibernate.dialect.lock.PessimisticEntityLockException: could not obtain pessimistic lock
at org.hibernate.dialect.lock.PessimisticWriteSelectLockingStrategy.lock(PessimisticWriteSelectLockingStrategy.java:102) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.lock(AbstractEntityPersister.java:1976) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.AbstractLockUpgradeEventListener.upgradeLock(AbstractLockUpgradeEventListener.java:82) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultLockEventListener.onLock(DefaultLockEventListener.java:83) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireLock(SessionImpl.java:673) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.fireLock(SessionImpl.java:667) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.access$1100(SessionImpl.java:197) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl$LockRequestImpl.lock(SessionImpl.java:2625) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.lock(SessionImpl.java:3433) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
... 34 common frames omitted
Caused by: org.hibernate.PessimisticLockException: could not extract ResultSet
at org.hibernate.dialect.H2Dialect$3.convert(H2Dialect.java:356) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.dialect.lock.PessimisticWriteSelectLockingStrategy.lock(PessimisticWriteSelectLockingStrategy.java:74) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
... 43 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLTimeoutException: Zeitüberschreitung beim Versuch die Tabelle {0} zu sperren
Timeout trying to lock table {0}; SQL statement:
select id from nachricht where id =? for update [50200-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:511) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.get(DbException.java:194) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.Command.filterConcurrentUpdate(Command.java:309) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.Command.executeQuery(Command.java:202) ~[h2-1.4.200.jar:1.4.200]
at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:114) ~[h2-1.4.200.jar:1.4.200]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
... 44 common frames omitted
Caused by: org.h2.message.DbException: Gleichzeitige Änderung in Tabelle "NACHRICHT": eine andere Transaktion hat den gleichen Datensatz geändert oder gelöscht
Concurrent update in table "NACHRICHT": another transaction has updated or deleted the same row [90131-200]
at org.h2.message.DbException.get(DbException.java:194) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.db.MVTable.convertException(MVTable.java:707) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.db.MVPrimaryIndex.lockRow(MVPrimaryIndex.java:232) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.db.MVPrimaryIndex.lockRow(MVPrimaryIndex.java:224) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.db.MVTable.lockRow(MVTable.java:567) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Select.isConditionMetForUpdate(Select.java:431) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Select$LazyResultQueryFlat.fetchNextRow(Select.java:1846) ~[h2-1.4.200.jar:1.4.200]
at org.h2.result.LazyResult.hasNext(LazyResult.java:101) ~[h2-1.4.200.jar:1.4.200]
at org.h2.result.LazyResult.next(LazyResult.java:60) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Select.queryFlat(Select.java:737) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Select.queryWithoutCache(Select.java:844) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Query.queryWithoutCacheLazyCheck(Query.java:201) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Query.query(Query.java:489) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.dml.Query.query(Query.java:451) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.CommandContainer.query(CommandContainer.java:285) ~[h2-1.4.200.jar:1.4.200]
at org.h2.command.Command.executeQuery(Command.java:195) ~[h2-1.4.200.jar:1.4.200]
... 48 common frames omitted
Caused by: org.h2.jdbc.JdbcSQLTransientException: Gleichzeitige Änderung in Tabelle "NACHRICHT": eine andere Transaktion hat den gleichen Datensatz geändert oder gelöscht
Concurrent update in table "NACHRICHT": another transaction has updated or deleted the same row [90131-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:626) ~[h2-1.4.200.jar:1.4.200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
... 64 common frames omitted
Caused by: java.lang.IllegalStateException: Map entry <table.16> with key <6909> and value [6909, TIMESTAMP '2020-02-19 10:16:29.992', NULL, 'a', 'TO_PORTALNUTZER', FALSE, 6857, 6906, NULL] 1/0 [6909, TIMESTAMP '2020-02-19 10:16:29.992', NULL, 'a', 'TO_PORTALNUTZER', FALSE, 6857, 6906, NULL] is locked by tx 1 and can not be updated by tx 2 within allocated time interval 2000 ms. [1.4.200/101]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:950) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.tx.TransactionMap.set(TransactionMap.java:316) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.tx.TransactionMap.lock(TransactionMap.java:263) ~[h2-1.4.200.jar:1.4.200]
at org.h2.mvstore.db.MVPrimaryIndex.lockRow(MVPrimaryIndex.java:230) ~[h2-1.4.200.jar:1.4.200]
... 61 common frames omitted
2020-02-19 10:17:33.467 ERROR 15652 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception
java.sql.SQLException: Connection is closed
at com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection.lambda$getClosedConnection$0(ProxyConnection.java:494) ~[HikariCP-3.4.2.jar:na]
at com.sun.proxy.$Proxy116.rollback(Unknown Source) ~[na:na]
at com.zaxxer.hikari.pool.ProxyConnection.rollback(ProxyConnection.java:375) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyConnection.rollback(HikariProxyConnection.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:116) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:561) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:836) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:810) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:649) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:370) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at de.lyth.compertis.kundenportal.repository.DownloadService$$EnhancerBySpringCGLIB$$a19d9494.downloadNachricht(<generated>) ~[main/:na]
at de.lyth.compertis.kundenportal.api.KundeController$1.writeTo(KundeController.java:312) ~[main/:na]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:111) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:98) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$4(WebAsyncManager.java:328) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-02-19 10:17:33.468 ERROR 15652 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection] with root cause
java.sql.SQLException: Connection is closed
at com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection.lambda$getClosedConnection$0(ProxyConnection.java:494) ~[HikariCP-3.4.2.jar:na]
at com.sun.proxy.$Proxy116.rollback(Unknown Source) ~[na:na]
at com.zaxxer.hikari.pool.ProxyConnection.rollback(ProxyConnection.java:375) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyConnection.rollback(HikariProxyConnection.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:116) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:561) ~[spring-orm-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:836) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:810) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:649) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:370) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99) ~[spring-tx-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at de.lyth.compertis.kundenportal.repository.DownloadService$$EnhancerBySpringCGLIB$$a19d9494.downloadNachricht(<generated>) ~[main/:na]
at de.lyth.compertis.kundenportal.api.KundeController$1.writeTo(KundeController.java:312) ~[main/:na]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:111) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBodyReturnValueHandler$StreamingResponseBodyTask.call(StreamingResponseBodyReturnValueHandler.java:98) ~[spring-webmvc-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$4(WebAsyncManager.java:328) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) ~[na:na]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-02-19 10:17:33.469  WARN 15652 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
2020-02-19 10:17:33.469 DEBUG 15652 --- [nio-8080-exec-6] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2020-02-19 10:17:33.471  WARN 15652 --- [nio-8080-exec-6] o.apache.catalina.core.AsyncContextImpl  : onError() call failed for listener of type [org.apache.catalina.core.AsyncListenerWrapper]
java.lang.IllegalArgumentException: Cannot dispatch without an AsyncContext
at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.StandardServletAsyncWebRequest.dispatch(StandardServletAsyncWebRequest.java:131) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.WebAsyncManager.setConcurrentResultAndDispatch(WebAsyncManager.java:391) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$2(WebAsyncManager.java:315) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.springframework.web.context.request.async.StandardServletAsyncWebRequest.lambda$onError$0(StandardServletAsyncWebRequest.java:146) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540) ~[na:na]
at org.springframework.web.context.request.async.StandardServletAsyncWebRequest.onError(StandardServletAsyncWebRequest.java:146) ~[spring-web-5.2.3.RELEASE.jar:5.2.3.RELEASE]
at org.apache.catalina.core.AsyncListenerWrapper.fireOnError(AsyncListenerWrapper.java:49) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.catalina.core.AsyncContextImpl.setErrorState(AsyncContextImpl.java:422) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:239) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.AbstractProcessor.dispatch(AbstractProcessor.java:237) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:59) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.30.jar:9.0.30]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-02-19 10:17:38.813 DEBUG 15652 --- [         task-5] d.l.c.k.repository.DownloadService       : Thread task-5 end download
2020-02-19 10:17:38.824 DEBUG 15652 --- [nio-8080-exec-8] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally

As you can see the first Thread (task-5) locks the entity, waits in my Thread.sleep
Second Thread (task-6) tries to lock the entity, gets SQLException because the row is locked and throws PessimisticLockException. So far so good! That’s the expected behavior from entityManager.lock. I want him to do that
But then I get java.sql.SQLException: Connection is closed and java.lang.IllegalArgumentException: Cannot dispatch without an AsyncContext in the first Thread, I think when the Transaction is beind handled and he is doing the rollback. I want to handle the PessimisticLockException and react to it accordingly (tell the user in the second Transaction why he couldn’t proceed)

When I switch from a H2 database to a PostgreSQL database, instead of throwing PessimisticLockException, the second Thread “waits” at the entityManager.lock, throws no PessimisticLockException at all

How to&Answers: