Transient vs Volatile modifiers in Java

By: Reema sen Emailed: 1790 times Printed: 2615 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Java defines two interesting type modifiers: transient and volatile. These modifiers are used to handle somewhat specialized situations.

When an instance variable is declared as transient, then its value need not persist when an object is stored. For example:

class T {
transient int a; // will not persist
int b; // will persist
}

Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the contents of b would. The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs.  In a multithreaded program, sometimes, two or more threads share the same instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable. The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state. To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

Note: volatile in Java has, more or less, the same meaning that it has in C/C++.

This is an extract from the book 'Java Complete Reference'. For more details please refer to the book


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(25)


1. View Comment

Your explanation is good and okay but, it will be better or most lovely only if you can try to and some real java program code to illustrate what you are talking about better.

View Tutorial          By: Emmanuel at 2009-05-28 02:45:11
2. View Comment

Your explanation is perfectly clear and not in need of "illustrative examples"! In particular, it succinctly makes clear that one should ALWAYS decorate an instance variable that is to be shared with "volatile".

View Tutorial          By: Percy at 2009-06-08 14:14:39
3. View Comment

Hi thanks for your information.

I got simple solution for my breath taking problem.

I am programming using java communication API with Serial port.
There data is recieved very fastly.Each time we have to get data in multi threading. It is very tedious to get all information sometimes.

Solution:
By using my variable with volatile i have fixed my problem.And my application is running with 100%.


View Tutorial          By: karthikeyan at 2009-09-18 04:50:37
4. View Comment

Hello,

A volatile variable does not have a copy maintained in the local memory of the thread (on the stack). All changes to the volatile variable (caused by multiple threads) are flushed out to the heap memory (visible from all threads). Hence volatile variable values remain consistent for all threads.

On the other hand, for other instance variables, each java thread maintains a local copy on the stack. Multiple threads may modify this local copy of the instance variable and hence inconsistent values may be visible for multiple threads.

For preventing this condition, we synchronize. During synchronization, a lock is first taken on the object monitor. Then the thread reads the state from the main memory and flushes its internal state. Subsequently, the synchronized code block/method code is executed. Once the execution completes, all the changes to the variables of that thread are flushed out to the main memory. Then the object monitor lock is released.

So, as we can see, volatile is a specialized case of synchronization. The only exceptions are, that it operates on a single field and no locks on the object monitor are required (as it operates on the heap memory and not the thread local stack memory).


View Tutorial          By: aayush at 2009-11-16 07:38:23
5. View Comment

If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

package javabeat.samples;

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();
}
}


View Tutorial          By: Prithvi at 2010-01-07 10:24:12
6. View Comment

You should consider using different threads that are not instantiated from the same class, but different classes. The volatile keyword does not work. The only workaround is to use another moitor class. I will try to sync and see if thqat will help.

View Tutorial          By: Jeremy at 2010-01-13 23:02:11
7. View Comment

If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

package javabeat.samples;

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();
}
}




Not Working i tried it... but


---------- run java ----------
Thread 1 : 0
Thread 2 : 0
Test Value : 0
Thread 2 : 1
Test Value : 0
Thread 1 : 1
Thread 1 : 2
Thread 2 : 2
Test Value : 0

Output completed (3 sec consumed)

<a href="http://www.itcareer.co.in">it career</a>


View Tutorial          By: it career at 2010-02-24 00:13:50
8. View Comment

Your explanation is good but, it will be better if you can try explain with some real java program code.

View Tutorial          By: Jabaraj at 2010-03-22 06:02:33
9. View Comment

This is an excerpt from Java Complete Reference.Just copy and paste technology

View Tutorial          By: Guest at 2010-03-25 01:36:57
10. View Comment

Explanation is very good. Thanks all.

View Tutorial          By: reddy at 2010-04-07 08:47:09
11. View Comment

The example is wrong, because there are two seperate instances of ExampleThread, so the testValue is not shared by the threads

View Tutorial          By: billGates at 2010-07-06 16:56:13
12. View Comment

This example is working fine....I think BillGates has misunderstood somewhere..

View Tutorial          By: Monoj Rath at 2010-07-15 01:27:51
13. View Comment

HI your explanation is absolutely correct but I am sure that it's copied from Complete reference Java2 fifth edition of Herbert Schildt.

View Tutorial          By: Anil R. Chinchawade at 2010-07-28 02:02:01
14. View Comment

Hi ,learn a new thing about These Transient and Volatile Modifiers .
Thanks to all of you.


View Tutorial          By: LakshmiNarayana Golla at 2010-07-28 02:49:48
15. View Comment

Can some body throw more light on TRANSIENT ....

View Tutorial          By: Anish at 2010-08-03 07:30:58
16. View Comment

Very good explaination of transient and volatile. Aayush reveals some important facts of volatile variable which clear doubts.
Thanks :)


View Tutorial          By: Himanshu Upadhyay at 2010-11-15 04:48:43
17. View Comment

What is transient keyword in Java?

What is Serilization?

If you want to understand what is transient, then first learn what is serilization concept in Java if you are not familiar with that. Serilization is the process of making the object's state persistent. That means the state of the object is converted into stream of bytes and stored in a file. In the same way we can use the de-serilization concept to bring back the object's state from bytes. This is one of the important concept in Java programming because this serilization is mostly used in the networking programming. The object's which are needs to be transmitted through network has to be converted as bytes, for that purpose ever class or interface must implements Serilization interface. It is a marker interface without any methods.

What is Transient?

By default all the variables in the object is converted into the persistent. In some cases, you may want to avoid persisting some variables because you don't have the necesscity to persist those varibale. So, you can declare those variables as transient. if the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.


View Tutorial          By: Mohit at 2010-11-18 00:26:24
18. View Comment

Real Life example of using Volatile
******************************************

class StackImpl {
private Object[] stackArray;
private volatile int topOfStack;

StackImpl (int capacity) {
stackArray = new Object[capacity];
topOfStack = -1;
}

public synchronized Object pop() {
System.out.println(Thread.currentThread() + ": popping");
while (isEmpty())
try {
System.out.println(Thread.currentThread() + ": waiting to pop");
wait(); // (1)
} catch (InterruptedException e) { }
Object obj = stackArray[topOfStack];
stackArray[topOfStack--] = null;
System.out.println(Thread.currentThread() + ": notifying after pop");
notify(); // (2)
return obj;
}

public synchronized void push(Object element) {
System.out.println(Thread.currentThread() + ": pushing");
while (isFull())
try {
System.out.println(Thread.currentThread() + ": waiting to push");
wait(); // (3)
} catch (InterruptedException e) { }
stackArray[++topOfStack] = element;
System.out.println(Thread.currentThread() + ": notifying after push");
notify(); // (4)
}

public boolean isFull() { return topOfStack >= stackArray.length -1; }
public boolean isEmpty() { return topOfStack < 0; }
}


View Tutorial          By: Mayank at 2011-01-25 15:44:21
19. View Comment

Hi there, I fixed the above (non-working) example:

package com.src.volatileExample;

public class MultiThreadingExample implements Runnable {

private volatile int testValue;

public void run()
{
for(int i=0; i<3; i++)
{
try
{
System.out.println(Thread.currentThread().getName()+": "+i);

if(Thread.currentThread().getName().equalsIgnoreCase("T1"))
{
testValue=10;
}
if(Thread.currentThread().getName().equalsIgnoreCase("T2"))
{
System.out.println("Test value: "+testValue);
}

Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

}

public class VolatileExmaple {

/**
* @param args
*/
public static void main(String[] args) {

MultiThreadingExample volatileExample = new MultiThreadingExample();

Thread t1 = new Thread(volatileExample,"T1");
Thread t2 = new Thread(volatileExample,"T2");

t1.start();
t2.start();

}
}


View Tutorial          By: JavaBoy at 2011-09-24 05:41:19
20. View Comment

i thnk exampleThread example is wrong - like billgates says.
the TestValue instance variable used by the two threads are from diffrernt objects. So, 'volatile' or not - they will always refer to two different variables - and hence not be in sync.


View Tutorial          By: oldman at 2011-09-24 12:32:33
21. View Comment

There was no sharing of volatile variable in the program. It just used the volatile instance variable. Each Thread created in the program having its own copy of that variable. there was no sharing

View Tutorial          By: Rajesh Poppoppu at 2011-12-30 13:04:42
22. View Comment

Awesome, now I can say I've fully understood volatile. thanks

View Tutorial          By: Andrew at 2012-01-13 18:19:15
23. View Comment

I think 19 floor's code doesn't fix the problem.Although the result is what we want to see.But assume that you remove the modifier volatile,the result is the same.So it doesn't make a difference whether the variable has a volatile...

View Tutorial          By: Benson at 2012-11-28 08:04:26
24. View Comment

it is really best site for the information.many time i open this site but it never hopeless me.

thanks


View Tutorial          By: panchanan ruata at 2013-05-22 09:36:37
25. View Comment

Updated example to better show Thread T2 showing the latest updated value in variable 'testValue'. And this example does work!!

public class VolatileExmaple {
public static void main(String[] args) {

VolatileTest instanceOfVolatileExample = new VolatileTest();

Thread t1 = new Thread(instanceOfVolatileExample, "T1");
Thread t2 = new Thread(instanceOfVolatileExample, "T2");

t1.start();
t2.start();

}
}

------------------

public class VolatileTest implements Runnable {

private volatile int testValue;

public void run() {
for (int i = 0; i < 20; i++) {
try {
//System.out.println(Thread.currentThread().getName() + ": " + i);
int randomInt = new Random().nextInt(20);
if (Thread.currentThread().getName().equalsIgnoreCase("T1")) {
testValue = new Random().nextInt(20);
System.out.println("T1 - Set Test value: " + testValue);
} else if (Thread.currentThread().getName().equalsIgnoreCase("T2")) {
if (randomInt < 9) {
try {Thread.sleep(100); } catch (Exception ignore) {}
}
System.out.println("T2 - Read Test value: " + testValue + "\n");
}

Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


View Tutorial          By: Sanjiv at 2013-05-25 20:26:31

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Reema sen
this keyword sample in Java
Using the DriverManager Class vs Using a DataSource Object for a connection
Steps to get a Free SSL certificate for your Tomcat
fgets(), fputs() - Line Input and Output - sample program in C
Address Arithmetic and pointers in C
Constants and escape sequences in C
Implementing Pure Virtual Functions in C++
strcat() and strncat() sample program in C++
paint() sample program to draw a line in J2ME
Creating and Handling JAR files
SequenceInputStream example program in Java
FilenameFilter - sample program in Java
Transient vs Volatile modifiers in Java
while (1) Loops in C++
Use of 'finally' in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
XML and Java - Parsing XML using Java Tutorial
Method Overriding in Java
Student marks calculation program in Java
InetAddress Example program in Java
Method Overloading (function overloading) in Java
FileReader and FileWriter example program in Java
Using StringTokenizer in Java
indexOf( ) and lastIndexOf( ) in Java
Count number of vowels, consonants and digits in a String in Java
Vector example in Java
Integer: byte, short, int, and long data types in Java
Text to Speech conversion program in Java
Using One-Dimensional Arrays in Java
How to use ArrayList in Java
Stack example in Java - push(), pop(), empty(), search()
Most Emailed Articles (in Java)
arraycopy() in Java
FilenameFilter - sample program in Java
How to use ArrayList in Java
indexOf( ) and lastIndexOf( ) in Java
Java program to check if user input is an even number
HTTPS Java - URL Connection program. Using HttpsURLConnection
for loop example in Java
Properties example in Java
HashMap example in Java
Use of - new - in Java
ZIP files in a folder and List files in a folder using Java Program
The OOP Principles
Handling Fractions in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program