Comment on Tutorial - Transient vs Volatile modifiers in Java By Reema sen

Comment Added by : Sanjiv

Comment Added at : 2013-05-25 20:26:31

Comment on Tutorial : Transient vs Volatile modifiers in Java By Reema sen
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");




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");

} catch (InterruptedException e) {

View Tutorial

Subscribe to Tutorials

Related Tutorials

Program using concept of byte long short and int 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

Archived Comments

1. I don't undrstnd.. cz I think in recurs the method
View Tutorial          By: Alina Ali at 2014-11-13 03:06:17

2. i want to need SCJD Dums. so please help me that w
View Tutorial          By: Dayamay singh at 2009-01-03 00:07:06

3. quite helpful
View Tutorial          By: kezyRoan at 2011-06-11 03:58:52

4. import java.util.Scanner;
public class Swit

View Tutorial          By: srinath at 2013-04-28 10:17:24

5. really nice and perfect ! thnak you very much for
View Tutorial          By: arash at 2013-07-16 10:58:45

6. Muy buen ejemplo, aunque como idea general podr&At
View Tutorial          By: Ligator at 2013-07-26 05:57:47

7. hi What is the meaning of this line ,
you c

View Tutorial          By: Anil Chalhotra at 2013-02-16 08:04:03

8. good job
View Tutorial          By: gopi at 2008-07-01 02:02:48

9. Hi,
Its good but you can make it more bette

View Tutorial          By: vishakha sharma at 2010-12-15 06:14:52

10. It's good but not easily understandable....
View Tutorial          By: koshal at 2010-12-19 23:32:05