This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: Difference between synchronized block and method in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Synchronized block and synchronized methods are two ways to use synchronized
keyword in Java and implement mutual exclusion on critical section of code.
Since Java is mainly used to write multi-threading programs, which present various kinds of thread related
issues like thread-safety,
deadlock
and race
conditions, which plagues into code mainly because of poor understanding of
synchronization mechanism provided by Java programming language. Java provides
inbuilt synchronized and volatile
keyword to achieve synchronization in Java. Main difference between synchronized method and synchronized block is
selection of lock on which critical section is locked. Synchronized method
depending upon whether its a static
method or non static locks on either class level lock or object
lock. Class level lock is one for each class and represented by class literal
e.g. Stirng.class. Object level lock is provided by current object
e.g. this instance, You should never
mix static and non static synchronized method in Java.. On the other hand
synchronized block locks on monitor evaluated by expression provided as
parameter to synchronized block. In next section we will see an example of both
synchronized method and synchronized block to understand this difference
better.