synchronized Java Keyword

The synchronized is a keyword defined in the java programming language.

synchronized Java Keyword

synchronized Java Keyword

     

The synchronized is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the synchronized keyword indicates the following :

-- The synchronized keyword may be applied to statement block or to a method.
--  The synchronized keyword provides the protection for the crucial sections that are required only to be executed by a single thread once at a time.
-- The synchronized keyword avoids a critical code from being executed by more than one thread at a time. Its restricts other threads to concurrently access a resource.
-- If the synchronized keyword is applied to a static method, as we will show it with a class having a method SyncStaticMethod through an example below, the entire class get locked while the method under execution and control of a one thread at a time.
-- When the synchronized keyword is applied to an instance method, as we have done with SyncMethod in the example given below, the instance get locked while being accessed and under execution and control of a one thread at a time.
-- When the synchronized keyword is applied to an object, then that object is locked though the code block associated with it get executed by one thread at at time.

Example to use the synchronized keyword within a class in java programming language:

public class Class1{
public synchronized static String SyncStaticMethod(){

}
public synchronized String SyncMethod(){

}

{

public class Class2{
Object Obj;
public String Method2(){
<statements>
synchronized (Obj){
<statements affecting Obj>
}
}
}