Search code examples
hibernategrailslockinggrails-ormpessimistic-locking

Pessimistic locking in grails 3+ lock()


    def check(){
        println"start first"
        Domain1 domain1=Domain1.get(1);
        domain1.lock();
        println "locking started"
        sleep(20*60)
        println "save first"
        domain1.name="hari ram"
        domain1.save();
        println "save first completed"

    }
    def check2(){
        try {
            println"start second"
            Domain1 domain1=Domain1.get(1);
            println"save second"
            domain1.name="hari ram -------------------++++++++"
            domain1.save(flush:true,failOnError:true);
            println "save second completed"
        }
        catch(Exception ex){
            ex.each{
                println "error ${ex}"
            }
        }
    }

My log from above code is :

start first
locking started
start second
save second
save second completed
save first
save first completed

And the database gets updated too. Why is lock() not working? isn't it that after lock() other instance is not able to update? Or is something else? or am i missing something?


Solution

  • Are you calling check and check2 with the same session? The lock() method selects the row for update (at the DB level), but if you come in in the same session and attempt to get the same object, you should be getting it from the hibernate session rather than going to the database and having to wait on the row to be released.

    I'm not positive this is your issue, but it looks like your code is right (though you'd be better using Domain.lock(1) to get and lock it at the same time in this example, there's nothing wrong with making the two calls separately).