0

I have a global number that gets incremented frequently but gets reset yearly. Right now I'm storing this global number as a single row:

class GlobalCounter {
    Integer counter = 0
    static constraints = {
    }
}

When I increment it, I use a lock in a transaction:

    def globalCounter = GlobalCounter.lock(1)
    globalCounter.counter = globalCounter.counter + 1
    globalCounter.save()
    globalCounter.discard()

The problem is that when I update it frequently, I get an exception instead of the code waiting:

Transaction (Process ID 61) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

I know that when you add a new row, the database gives the option of using a primary key with auto increment, so I think this should be possible without deadlocks. How can I do it?

Anonymous1
  • 3,877
  • 3
  • 28
  • 42

0 Answers0