10 things you must know about synchronization in java

I would like to share some key points about synchronization in java which will be beneficial while coding and for interview also.

Key points about synchronization in java



1. Each object has only one lock.

2. Only methods or blocks can be synchronized , you cannot synchronize the variables or classes. You cannot apply synchronized keyword with variables and also you can not use volatile keyword with method.

3. A class can have both synchronized and non synchronized methods.

4. Once one thread acquires a lock on any object, no other thread can enter any of the synchronized methods in that class.

5. Suppose if class have both synchronized and non synchronized methods, multiple threads can access the non synchronized methods.

6. Static methods can be synchronized. There is a chance that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.

7. If thread goes to sleep, it holds the locks and do not release it.







8. A thread can acquire multiple locks. Suppose one thread has acquired lock by entering into the synchronized method of one object , it can invoke synchronized method on a different object, thus acquiring lock on another object as well. JVM also allows a thread to acquire a lock by entering into the synchronized method on the same object.

9. You can synchronize a block of code rather than a method.

Following code snippet shows example of synchronizing a block of code.

Example of synchronizing a block of code


class SyncEx{
public void syncBlockEx(){
   System.out.println("This part is not synchronized.");
   synchronized( this ){ //synchronizing a block of code
     System.out.println("This part is synchronized.");
   }
}

You should not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects.

10 . When we consider synchronization in Java, the important methods we need are wait(), notify() and notifyAll() which is defined in Object class. (why wait(), notify() and notifyAll() are defined in Object class?)


Hope I have listed some important key points about synchronization in java, if you like to add more , you can add it via comment. And if you like the the article, share it with your friends.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment