Skip to content

Instantly share code, notes, and snippets.

@arcesino
Created March 22, 2014 22:16
Show Gist options
  • Save arcesino/9715288 to your computer and use it in GitHub Desktop.
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
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