0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good to know. One more doubt : We cannot use synchronized block[ synchronized(this){} ] in static context, can we create a static variable say myStatic and use synchronized(myStatic) ? That will guarentee synchronization there right ?
@SrikanthPai: Yes, so long as both threads synchronize against the same reference. Personally I try to avoid synchroizing on this in instance methods... I prefer creating objects which are only used for synchronization, as that makes it easier to reason about them, knowing that the only code that has access to the monitor is the code in the class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.