10

I understand a synchronized block or method will block all threads until the one inside has "left". I am wondering, can context switching happen when thread is executing inside synchronized block? In my understanding, it shouldn't.

Thanks!

1
  • 3
    Yes, context switching can happen as it is handled by OS and not JVM Nov 23, 2013 at 13:47

5 Answers 5

13

can context switching happen when thread is executing inside synchronized block?

Yes, a context switch can happen inside a synchronized block as well. The only thing that's going to be different is that no other thread would be able to enter the same synchronized block (or any other block synchronized on the same object) until the context switches back to that pre-empted thread, letting it finish with its protected code.

0
5

What you understand is wrong. A synchronized block doesn't block other threads. A synchronized block only prevents other threads from entering a block that is synchronized on the same object. Other threads continue running while a synchronized block is being executed.

And of course, context switching can happen while in the synchronized block, because other threads must also have some time to execute themselves. If that was not the case, two synchronized blocks running for a few seconds would block everything else on a 2-core machine. You really don't want that to happen.

2
  • My understanding of blocking of threads outside synchronized block is correct, perhaps your understanding of my question was incorrect. Thanks for your answer about context switching, it make sense.
    – Abidi
    Nov 23, 2013 at 18:51
  • I can only judge your understanding by what you post. And you posted I understand a synchronized block or method will block all threads until the one inside has "left", which is clearly not what synchronized does.
    – JB Nizet
    Nov 23, 2013 at 22:17
2

Context switch can happen inside the synchronized. Such as we can call sleep() or wait() method in synchronized block. Either sleep() or wait() make current thread unrunnable.

0

Think thread switch and synchronize are 2 complete different things. Synchronize just takes care about sharing of ressources not more not less. Another thread could do something complete different. So both are not related.

-2

The main reason that you use synchronized block is context switching done by OS actually! If there were no context switching, there were no need for a synchronized block either.

Actually no context switching means no thread support! Yes, it's true about MS-DOS, but not any modern OS!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.