Example & Tutorial understanding programming in easy ways.

What is use of synchronized keyword?

Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition.

E.g.

public void synchronized method(){} 
public void synchronized staticmethod(){}
public void myMethod(){

            synchronized (this){             // synchronized keyword on block of  code
            }

}

Read More →