Suppose there are TWO Threads A and B . There is one object which has 2 synchronized methods dothisOne and dothisTwo which should get executed in the order (dothisOne--->dothisTwo) in the calling program. Both the threads have to follow the same calling sequence(dothisOne--->dothisTwo) . Suppose both start fresh and first thread A locks the object while performing dothisOne. Once it finishes dothisOne and control comes out ...Are there chances of ThreadB starting dothisOne (or) is it 100% guarenteed that thread A will go for dothisTwo ? This question is related to instance method . If it was class method(static), I believe threadA would go for dothisTwo
Are there chances of ThreadB starting dothisOne (or) is it 100% guarenteed that thread A will go for dothisTwo ?
No guarantees at all. I suspect it's more likely that thread A will get to go into doThisTwo
instead, because basically there's nothing it needs to do between exiting the monitor and re-entering it - it doesn't need to be rescheduled or anything. But no, it can happen either way.
If it was class method(static), I believe threadA would go for dothisTwo
Nope - synchronization doesn't care about instance methods vs static methods. Static and instance synchronized methods differ in which monitor they implicitly synchronize against, but that's all.
Basically, if you want two things to happen as a unit (in terms of synchronization), you need to synchronize around the pair of operations, rather than just each operation in turn.
See more on this question at Stackoverflow