|
Declaring a method as synchronized restricts the threads to access it. Only one thread can execute it at a time. Therefore, synchronized methods are performance overhead. Note that you should declare methods as synchronized when it is absolutely essential. For correctness, all the methods that modify the shared information in any way should be declares as synchronized. All the other methods, including the methods that simply access the shared information, need not be synchronized. For instance, if we would be printing the account details using a method printBillDetails() as:
private void printBillDetails(Account ) {
System.out.println(“Utility bill for ” + account.getCutomerName());
System.out.println(“Total amount due … “ + account.getAmountDue());
// print other details
}
We need not make this method synchronized as this method is merely accessing the account details. It is not modifying them.
|
|
Java does not declare the variables as synchronized. Only methods (and code blocks) can be declared as synchronized. The data in variables cannot be modified without a method or code block. Hence, you can protect it from simultaneous access with the help of synchronized access. |