{"id":12714,"date":"2015-10-20T12:52:00","date_gmt":"2015-10-20T11:52:00","guid":{"rendered":"https:\/\/touk.pl\/blog\/?guid=d8407e35a8f76726cc313f1b9c76b4ac"},"modified":"2022-07-28T14:20:42","modified_gmt":"2022-07-28T12:20:42","slug":"how-to-recover-after-hibernates-optimisticlockexception","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2015\/10\/20\/how-to-recover-after-hibernates-optimisticlockexception\/","title":{"rendered":"How to recover after Hibernate&#8217;s OptimisticLockException"},"content":{"rendered":"<p>I&#8217;ve read many articles about optimistic locking and OptimisticLockException itself. Problem is that each one of them ended up getting their first exception and no word on recovery. What to do next? Repeat? If so, how? Or drop it? Is there any chance to continue? How? Even more, documentation says that if you get Hibernate exception &#8211; you&#8217;re done, it&#8217;s not recoverable:<\/p>\n<blockquote><p>An exception thrown by Hibernate means you have to rollback your database transaction and close the Session immediately (this is discussed in more detail later in the chapter). If your Session is bound to the application, you have to stop the application. Rolling back the database transaction does not put your business objects back into the state they were at the start of the transaction. This means that the database state and the business objects will be out of sync. Usually this is not a problem, because exceptions are not recoverable and you will have to start over after rollback anyway.<\/p>\n<footer>&#8211; <cite><a href=\"https:\/\/docs.jboss.org\/hibernate\/orm\/4.3\/manual\/en-US\/html\/ch13.html#transactions-optimistic\">Hibernate 4.3 documentation, 13.1.4<\/a><\/cite><\/footer>\n<\/blockquote>\n<p>Here is my attempt on this: <strong>repeatable<\/strong> and <strong>recoverable<\/strong>.<\/p>\n<h3 id=\"business-case\">Business case<\/h3>\n<p>Let&#8217;s say we have distributed application with two web servers, connected to the same database. Applications use optimistic locking to avoid collisions. Customers buy lottery coupons, which are numbered from 1 to 100. In the same second Alice on web server 1 draws two coupons: 11 and 12. In the same moment Bob reserves two coupons on web server 2. It draws 11 and 13 for Bob and tries to write it back to database. But it fails, since Alice&#8217;s commit was first. I want a web application server to draw coupons for Bob again and then &#8211; try to save again until it succeeds.<\/p>\n<h3 id=\"solution\">Solution<\/h3>\n<p>For every request Hibernate associates different Session that is flushed at the end of request processing. If you hit OptimisticLockException then this Request Session is polluted and will be rolled back. To avoid this we will create a separate Hibernate&#8217;s Session especially for drawing coupons. If separate session fails &#8211; drop this session and try again in a new one. If it succeeds &#8211; merge it with a main request session. Request Session cannot be touched during draws. Take a look at the following picture:<\/p>\n<div class=\"separator\" style=\"clear: both;text-align: center\"><a style=\"clear: both\" href=\"http:\/\/3.bp.blogspot.com\/-ZR17MHsMtuQ\/ViYBDrtFpcI\/AAAAAAAAA8w\/cFiDRvtdNvs\/s1600\/optimistic%2Blocking%2B2.png\"><img decoding=\"async\" src=\"http:\/\/3.bp.blogspot.com\/-ZR17MHsMtuQ\/ViYBDrtFpcI\/AAAAAAAAA8w\/cFiDRvtdNvs\/s1600\/optimistic%2Blocking%2B2.png\" border=\"0\" \/><\/a><\/div>\n<p>On this picture yellow and green short-term sessions has failed with OptimisticLockException. Red session was successful and these objects are merged to a main session on the left.<\/p>\n<h4 id=\"reservation-entity\">Reservation entity<\/h4>\n<p>Key requirement here is to keep a domain you want to lock on as small as possible and not coupled directly to anything else. Best approach here is to create some <code><span class=\"class\">Reservation<\/span><\/code> entity with few fields, let&#8217;s say: <code><span class=\"field\">couponId<\/span><\/code> and <code><span class=\"field\">customerId<\/span><\/code>. For each <code><span class=\"class\">Coupon<\/span><\/code> create one <code><span class=\"class\">Reservation<\/span><\/code> row and use <code><span class=\"field\">reserved<\/span><\/code> boolean field as a reservation status. For coupon and customer use weak identifiers (<code><span class=\"keyword\">long<\/span><\/code>) instead of real entities. This way no object tree will be loaded and <code><span class=\"class\">Reservation<\/span><\/code> stays decoupled.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import\u00a0 lombok.extern.slf4j.Slf4j;\r\nimport\u00a0 org.hibernate.*;\r\nimport\u00a0 org.hibernate.ejb.HibernateEntityManager;\r\nimport\u00a0 org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;\r\n\r\nimport\u00a0 javax.persistence.OptimisticLockException;\r\nimport\u00a0 javax.persistence.PersistenceContext;\r\nimport\u00a0 java.util.List;\r\n\r\n@Slf4j\r\npublic class\u00a0 ReservationService\u00a0 {\r\n\r\n    @PersistenceContext\r\n    private\u00a0 HibernateEntityManager\u00a0 hibernateEntityManager;\r\n\r\n    @SuppressWarnings(\"uncheked\")\r\n    private\u00a0 Iterable &lt; Reservation &gt; \u00a0reserveOptimistic(long\u00a0 customerId, \u00a0final int\u00a0 count)\u00a0 throws\u00a0 NoFreeReservationsException\u00a0 {\r\n        log.info(\"Trying to reserve {} reservations for customer {}\", \u00a0count, \u00a0customerId);\r\n\r\n        \/\/This is the request session that needs to stay clean\r\n        Session\u00a0 currentSession = \u00a0hibernateEntityManager.getSession();\r\n        Iterable &lt; Reservation &gt; reserved = \u00a0null;\r\n\r\n        do\u00a0 {\r\n            \/\/This is our temporary session to work on\r\n            Session\u00a0 newSession = \u00a0hibernateEntityManager.getSession().getSessionFactory().openSession();\r\n            newSession.setFlushMode(FlushMode.COMMIT);\r\n            Transaction\u00a0 transaction = newSession.beginTransaction();\r\n\r\n            List &lt; Reservation &gt; availableReservations = \u00a0null;\r\n\r\n            try\u00a0 {\r\n                Query\u00a0 query = newSession.createQuery(\"from\u00a0Reservation\u00a0r where r.reserved\u00a0= false\")\r\n                    .setLockMode(\"optimistic\", \u00a0LockMode.OPTIMISTIC)\r\n                    .setMaxResults(count);\r\n\r\n                availableReservations = query.list();\r\n\r\n                \/\/There is no available reservations to reserve\r\n                if\u00a0 (availableReservations.isEmpty()) {\r\n                    throw new\u00a0 NoFreeReservationsException();\r\n                }\r\n\r\n                for\u00a0 (Reservation\u00a0 available: availableReservations) {\r\n                    available.reserve(customerId);\r\n                    newSession.save(available);\r\n                }\r\n\r\n                \/\/Commit can throw optimistic lock exception if it fails\r\n                transaction.commit();\r\n\r\n                \/\/Commit succeeded - this reference is used outside try-catch-finally block\r\n                reserved = availableReservations;\r\n\r\n            }\u00a0\r\n            catch\u00a0 (OptimisticLockException\u00a0 | \u00a0StaleObjectStateException\u00a0 | \u00a0HibernateOptimisticLockingFailureException\u00a0 e) {\r\n                log.info(\"Optimistic lock exception occurred for customer {} and count {}: {} {}\", \u00a0customerId, \u00a0count, \u00a0e.getClass(), \u00a0e.getMessage());\r\n\r\n                transaction.rollback();\r\n\r\n                for\u00a0 (Reservation\u00a0 availableMsisdn: availableReservations) {\r\n                    newSession.evict(availableMsisdn);\r\n                }\r\n            }\u00a0\r\n            finally\u00a0 {\r\n                newSession.close();\r\n            }\r\n            \/\/Repeat until we reserve something\r\n        }\u00a0 while \u00a0 (reserved == \u00a0null);\r\n\r\n        log.info(\"Successfully reserved {} reservations for customer {}\", \u00a0count, \u00a0customerId);\r\n\r\n        \/\/Merge reserved entities to request session\r\n        for\u00a0 (Reservation\u00a0 reservedMsisdn: reserved) {\r\n            currentSession.merge(reservedMsisdn);\r\n        }\r\n\r\n        return\u00a0 reserved;\r\n    }\r\n}<\/pre>\n<p>This code says it all. It tries to reserve some <code><span class=\"class\">Reservation<\/span><\/code>s until it succeeds in a do-while loop. Main Request Session is not polluted and it achieves our goal.<\/p>\n<p>I hope this example helps you in similar cases. It works as expected for a few months on our customer&#8217;s production site and I recommend this solution.<\/p>\n","protected":false},"excerpt":{"rendered":"I&#8217;ve read many articles about optimistic locking and OptimisticLockException itself. Problem is that each one of them ended up getting their first exception and no word on recovery. What to do next? Repeat? If so, how? Or drop it? Is there any chance t&#8230;\n","protected":false},"author":37,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[43,68,51],"class_list":{"0":"post-12714","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design","7":"tag-hibernate","8":"tag-java","9":"tag-jpa"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12714","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/37"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=12714"}],"version-history":[{"count":13,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12714\/revisions"}],"predecessor-version":[{"id":14646,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12714\/revisions\/14646"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=12714"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=12714"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=12714"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}