Synchronized block is alternative mechanism for "synchronized" methods.If we inherihate the non synchronized blocks either from base class or interface inface into our derived class and the inheriated non-synchronized method is trying to accessed by multiple threads then we get inconsistent result.To avoid this inconsistent result, the derived class programmer is attempting to write "synchronized" keyword before non synchronized method to make the method is synchronized which is not possible because one cannot change the prototype of base class methods in the context of derived class. Hence the synchronized method concept is unable to the solve the above problem therefore to solve the above problem for getting the consistence we use a concept called "synchronized blocks". Synchronized blocks must be always written in the definition of non-synchronized method.
syntax:
synchronized(object of current class){
//Block of statements;
}
It is not possible to override static methods but it is possible to override the instance methods.synchronized blocks must be always written in non-synchronized instance methods only.
Example:
package ip;public interface Account{
void deposit(int amt);
}
class SAccount implements Account{
int bal=0;
public void deposit(int amt){
synchronized(this){
bal = bal + amt;
System.out.println("user Account bal="+bal);
}
}