While most of the discussion has focused on the synchronization I didn't think they really discussed the difference. So let's look at how block and method synchronization are the same.
public synchronized method( Param param ) {
// do some work in here
}
public method( Param param ) {
synchronized( this ) {
// do some work here
}
}
These two methods are the exact same. Notice there is no code above or below the synchronized block. If they were the some code outside the block that code would be executed by multi-threads. Another distinction between them is that you can alter between code that runs without locking and code that runs under locking. This can be used to boost performance if only a small portion needs to run under locking, and the meat of the method can run multi-threaded boosting performance if that portion is a hotspot. Now let's see how blocks can offer more granularity of synchronization than methods.
public synchronized method1( Param param ) {
// do something unrelated to method 2
}
public synchronized method2( Param param ) {
// do something unrelated to method 1
}
In this case method1 AND method2 would only allow a thread at once in either of them at a time because synchronized methods lock on this. Of course if we synchronized on this in a block it would be the same. However, we don't have to synchronize on this always. Here is a way to make method1 and method2 locking independent.
Object method1Lock = new Object();
Object method2Lock = new Object();
public method1( Param param ) {
synchronized( method1Lock ) {
// do stuff
}
}
public method2( Param param ) {
synchronized( method2Lock ) {
// do stuff
}
}
This is important distinction because now method1 and method2 can be executed simultaneously where using synchronized methods will not allow this. You have to keep in mind that method1 and method2 MUST be independent in their code. If method1 modifies an instance variable, and method2 reads that variable they aren't independent, and you must use method synchronization. However, if method1 accesses separate instance variables than method2 then this technique can be used. What does that all mean? Neither technique is superior to the other. Method synchronization is simple and straight forward, but might have lower performance because it locks too much. Block synchronization fixes that problem, but its more complex.
Synchronization is important. There are problems that can't be done with out it. However, it's best to be careful, and try very hard to not use it when you don't have to. There are some great techniques that eliminate locking, and can improve throughput so you have to know when to use those as well. This all just takes experience and wisdom. Good luck.