What is the difference between synchronized block and synchronized method ?

What is the difference between synchronized block and synchronized method ?

Both the synchronized method and block are used to acquires the lock for an object. When you mark a method synchronized, then you are forcing every thread which calls that method to lock the monitor. If you expect a synchronized() {} block in the calling code, it is possible that some code which calls your method might neglect to
use synchronized() and end up with a threading problem in your program. synchronized code always use objects as locks to prevent other threads from entering the synchronized block. For instance methods, they are synchronized on the \'this\' reference, and for static methods they are synchronized on the instance of the Class object method belongs to. Best practice is to minimize the code inside synchronized blocks because they prevent concurrent threads from executing - losing any advantage of multi-threaded applications. Synchronized blocks help let those portions of a method that do not access shared resources to be run simultaneously while still keeping those parts that need to be shared thread-safe.

By:Jalees
Date:2015-01-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related Java Subjective Links

Java Subjective interview questions and answers for experienced and fresher