This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Java synchronized block is better than java synchronized method in java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance. A good example of java synchronization around this concept is getInstance() method Singleton class.
my question is that the link says, synchronization block locks critical section of code(highlighted in bold in above paragraph). my confusion is that don't we lock objects as opposed to section of code. also the kb6 book says that once we enter a synchronized method we acquire lock on the object whose method code we are running, and further , no other thread is allowed to enter any other SYNCHRONIZED METHOD of that object(non synchronized methods can be accessed by multiple threads). so my question is that when we use synchronization blocks and we acquire a lock on an object , say which does not have any synchronized method, then what is the thing on which we get mutual exclusive access ?
You are right that synchronization acquires lock on an object. Lets see it this way. Here's a method in which there are some thread safe statements (which don't need synchronization) and some thread unsafe statements (which needs synchronization). (Note: Don't try to make out any meaning of this code its just my imagination at run )
Now synchronizing the method is like synchronizing all the statements in the method in a synchronized block
But the first 2 operations don't need synchronization and can be performed by 2 threads simultaneously. So its better that I don't synchronize those two statements
This flexibility is only there in synchronized blocks...
DCLs are not the only way to expose a Singleton instance. Take a look at the book 'Effective java' to explore this topic a little more. (Not related to the cert in any way, but it is a great source of good design principles)