Skip to main content

Volatile keyword in JAVA

I've found an interesting and easy to understand explanation about volatile keyword, it came with an example but it was wrong so I've corrected it.
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).
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. 

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(Thread.currentThread().getName() + " : " + i);
if (Thread.currentThread().getName().equalsIgnoreCase("T1")) {
 System.out.println("Test Value T1: " + testValue);
 testValue = 10;
}
if (Thread.currentThread().getName().equalsIgnoreCase("T2")) {
 System.out.println("Test Value T2: " + testValue);
 testValue = 20;
}
Thread.sleep(1000);
 } catch (InterruptedException exception) {
exception.printStackTrace();
 }
}
  }
}

public class VolatileExample {
  public static void main(String args[]) {
ExampleThread exampleThread = new ExampleThread("Thread 1 ");
Thread t1 = new Thread(exampleThread, "T1");
Thread t2 = new Thread(exampleThread, "T2");
t1.start();
t2.start();

  }
}

Comments

Popular posts from this blog

Quarkus goes Reactive☢

In this tutorial I will explain how to create a quarkus based java application that will use reactive datasource to connect to a postgres database and be able to perform crud operations via rest endpoint. To make it more real this application will also be published into kubernetes cluster and will use configmap to store datasource configuration. To lern more about benefits of reactive data sources vs. jdbc regular data sources you can go to following link https://cutt.ly/1l260tK.  Step 1: Configure Project 

Configuring web application with gwt+spring+hibernate

Building a web application using hibernate, spring and gwt. This time we will show how to create and cofigure an application that will use hibernate , spring and gwt. I will use HR sample database that comes with OracleXE. First , you have to create a GWT project (you can follow the steps for that on  https://developers.google.com/web-toolkit/ ) After you have the project created you need to create a tree of packages like that: Open HumanResources.gwt.xml and add the following line : By doing that you tell gwt to include model package and all dependent packages into gwt compilation Now we can start configuring spring and hibernate. to configure spring first you have to add the following lines on web.xml This will allow spring context to start doing its business. The you will have to create a field called "app-config.xml" in which you will define the settings for spring and hibernate. Over this app-config file first configure the properties as follo...

Configuring web application with gwt+spring+hibernate (continued)

Last Time we learned how to configure a hibernate+ spring+ GWT application. Now we will continue explaining how I built this  application. First, we'll start with the Beans. For this example we will define one bean called Regions and an interface called Bean . Region will be the pojo class that contains the mapping for HR schema regions table The  @Entity  annotation is used to mark this class as an Entity bean. To use this annotation the class must have at least a package scope no-argument constructor. The  @Table  annotation is used to specify the table to persist the data. The  name  attribute refers to the table name. If  @Table  annotation is not specified then Hibernate will by default use the class name as the table name. The  @Id  annotation is used to specify the identifier property of the entity bean. The placement of the @Id  annotation determines the default access strategy that Hibernate will use f...