The synchronized and volatile modifiers

The synchronized and volatile modifiers

Previous Home Next

 

Synchronized modifier:-The synchronized modifier is used in multithreaded programming to control access to critical sections in the program.

Volatile modifier:-In java the volatile modifier only applies to instance variables just like the transient modifier.
The variables declared volatile are subject to asynchronous modifications.

Synchronized modifier

The synchronized modifier is used in multithreaded programming to control access to critical sections in the program.The synchronized keyword used to indicate that a method can be accessed by only one thread at a time.
The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier is generally used mainly in threading environment.

Volatile modifier

In java the volatile modifier only applies to instance variables just like the transient modifier.
The variables declared volatile are subject to asynchronous modifications. Thus we can say that,
declaring a variable volatile tells the compiler that this variable might be changed unexpectedly by other part of the program.
 Synchronized Syntax

public synchronized void showDetails()  // any of the four modifiers are used with synchronized .
{
.......
}

Volatile Syntax

public static final int VOLATILE
{
.......
}

    //The int value representing the volatile modifier.


 
VOLATILE MODIFIER

public class
MyRunnable implements Runnable
{
private volatile boolean active; // declaring volatile variable

public void run()
{
active = true;
while (active) // line 1
{
// some code here
}
}
public void stop()
{
active = false; // line 2
}
}

Synchronized modifier

public synchronized void showDetails()
{
.......// some code written here
}






Previous Home Next