0

This was one of the interview questions I was asked in an interview. In java most of the stuff that we can do with synchronized methods, can also be done with synchronized blocks. So, why does java provide 2 variations of the same mechanism?

I thought of the below reason. 1. we can make blocks as small as possible with a lock of our choice(this or someother object), where as, for methods it is a complete method (could be small or big) and always acquires the lock on this or class( for static methods).

Can somebody tell me what else could be the reason?

My apologies if this was posted already.

Raj
  • 1

1 Answers1

1

Synchronized block provides the locking at granular level as you said.

Also synchronized method gets lock on current object (which may be required or not depending what you want to achieve) but with synchronized block you have liberty to take lock on other object, hence threads can enter other instance method of this object

M Sach
  • 33,416
  • 76
  • 221
  • 314