Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Volatile Variable

Posted By: Will Thompson     Category: Java     Views: 4974

This article explains about volatile variable in java with example.

Volatile variables are treated different from other variables. When you mark a variable as volatile, this warns the compiler to get fresh copies of the variable rather than caching the variable in the registers. value of volatile variable can be changed unexpectedly.

Syntax of Volatile Variable

volatile type varName = value; 

type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value. 

Example of Volatile Variable

Example 1 : Program that illustrates volatile variable use in java 

class ExampleThread extends Thread 
{
private volatile int testValue;

public ExampleThread(String str)
        {
super(str);
}
        public void run() 
        {
for (int i = 0; i < 3; i++) 
                {
try 
                        {
System.out.println(getName() + " : "+i);
if (getName().equals("Thread 1 "))
{
testValue = 10;
}
if (getName().equals("Thread 2 "))
{
System.out.println( "Test Value : " + testValue);
}
Thread.sleep(1000);
                        catch (InterruptedException exception) 
                        {
exception.printStackTrace();
}
}
}
}

public class VolatileExample 
{
public static void main(String args[]) 
        {
new ExampleThread("Thread 1 ").start();
new ExampleThread("Thread 2 ").start();
}
}

  
Share: 

 
 

Didn't find what you were looking for? Find more on Volatile Variable Or get search suggestion and latest updates.

Will Thompson
Will Thompson author of Volatile Variable is from Perth, Australia.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!