Java Synchronized Keyword
In this tutorial, we will learn about synchronized keyword in Java, importance of it and how to use it along with syntax and a working example of it.
synchronized keyword
The synchronized
keyword in Java is used to provide mutually exclusive access on shared resources, at a time only one thread can access this mutually exclusive shared resource and this is very important in case of multi-threaded application to prevent race conditions and other data inconsistency issues.
In Java, we have a flexibility to declare mutually exclusive access for a Class or Objects or any data members of a class excluding primitive data-types.
Synchronizing access to an object's method: In this case, the synchronized keyword is used to ensure that only one thread at a time can execute a method on an object. This is achieved by acquiring a lock on the object when the method is called, and releasing the lock when the method returns.
Method level synchronized keyword syntax:
public synchronized void synchronizedMethod() {
}
Synchronizing access to a class method: In this case, the synchronized keyword is used with combination of static keyword which ensures class level lock. At a time only a single thread can get an access to the resource although different objects of same type are trying to access.
Class level synchronized keyword syntax:
public static synchronized void synchronizedClassMethod() {
}
Synchronizing access to block of method: In this case, the synchronized keyword is used within the method to ensure block level access for data-members of a class. This allows to give a mutually exclusive lock on to the specific data-members.
Block level synchronized keyword syntax:
public void synchronizedBlockOfMethod() {
synchronized(this.data_member) {
}
}
It is important to note that excessive use of synchronization can lead to performance issues in a multi-threaded environment. Therefore, it is important to carefully consider the use of synchronization and use it only when its absolute necessary.
Conclusion:
In this tutorial, we have learned about synchronized keyword and its importance along with the syntax and types of synchronization.