Created
March 22, 2014 22:16
-
-
Save arcesino/9715288 to your computer and use it in GitHub Desktop.
A dynamic method for deal with Optimistic Locking in Grails with retries & timeout. Please consider the following for a correct usage: 1) Call withOptimisticLocking outside any transaction, 2) Ensure only one transaction is created inside withOptimisticLocking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
grailsClass.metaClass.withOptimisticLocking = { Long timeout = 3000L, Closure cls -> | |
def startTime = new Date().time | |
def duration = 0 | |
def attempts = 0 | |
while (true) { | |
try { | |
attempts++ | |
cls.call() | |
break | |
} catch (OptimisticLockingFailureException e) { | |
duration = new Date().time - startTime | |
if (duration > timeout) { | |
log.warn("withOptimisticLocking timeout! attempts = ${attempts}") | |
throw e | |
} | |
} | |
} | |
duration = new Date().time - startTime | |
log.info("withOptimistickLocking success! attempts = ${attempts}, duration = ${duration}") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment