2
    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?

Daniel
  • 3,312
  • 1
  • 14
  • 31
ujjwol shrestha
  • 145
  • 1
  • 12
  • missing a lot start with https://stackoverflow.com/questions/9301395/grails-what-does-saveflushflush-inserttrue-do-differently-from-saveflus – V H Aug 24 '17 at 13:09
  • @vahid have tried flushing as well – ujjwol shrestha Aug 24 '17 at 13:15
  • I think there is a lot you are not understanding. I think the lock method is designed to work within a trail of transactions - something calls something locks it does something returns checks lock and so on it is all part of the same transaction but obviously more complex than you have imagined above. The fact you are doing something 1 place then calling another `transactional` - hard to know since the above looks like all from a controller call and this time issuing a flush:true - telling it that it must do this – V H Aug 24 '17 at 15:02

1 Answers1

1

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).

Trebla
  • 1,164
  • 1
  • 13
  • 28