Skip to main content

When should I use volatile modifier?

--
A variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile.


The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads. For example, A multiprocessor system(>2 CPUs) with 2 threads sharing a single variable in memory.
  • Thread 1 reads the variable and caches it in one of the registers for efficient access.
  • Thread 2 reads the memory and changes its value.
  • Now if Thread 1 wants to access the value, it may get it from its cache and thus end up with a wrong value.
To avoid these scenarios a variable can be declared as volatile, thus informing the JVM that the value can change asynchronously and has to be fetched always from memory or in other words it is like saying to JVM "Please do not optimize this variable for any reason".

synchronized vs. volatile

It is important to understand that atomic operations do not automatically mean thread-safe operations. In addition, whenever multiple threads share variables, it is important that they are accessed in a synchronized method or block, or are declared with the volatile keyword. This ensures that the variables are properly reconciled with main memory, thereby guaranteeing correct values at all times.

Whether you use volatile or synchronized depends on several factors. If concurrency is important and you are not updating many variables, consider using volatile. If you are updating many variables, however, using volatile might be slower than using synchronization. Remember that when variables are declared volatile, they are reconciled with main memory on every access. By contrast, when synchronized is used, the variables are reconciled with main memory only when the lock is obtained and when the lock is released.

Consider using synchronized if you are updating many variables and do not want the cost of reconciling each of them with main memory on every access, or you want to eliminate concurrency for another reason.
The following summarizes the differences between the synchronized and volatile keywords.
  • synchronized
    • Pro: Private working memory is reconciled with main memory when the lock is obtained and when the lock is released.
    • Con: Eliminates concurrency.
  • volatile
    • Pro: Allows concurrency. The visibility of the changes made by a thread to the content of the variable respect others threads
    • Con: Private working memory is reconciled with main memory on each variable access.
  • The volatile has nothing to do with preventing simultaneous execution of a portion of code but synchronized does.

Why can not a variable be volatile and final?

A volatile variable means it could be changed by several threads so a thread should always reconcile the value with what is saved in memory rather than assume that the variable it finds is valid. If a variable is final it can't be changed so there is no reason to need to reconcile values. Thus volatile and final are contradictory in a way. It doesn't make sense to be able to combine them thus java does not allow it.

References

Use Synchronized or Volatile when Accessing Shared Variables by Peter Hagger

Comments

Popular posts from this blog

Asynchronous Vs. Synchronous Communications

Synchronous (One thread):   1 thread -> |<---A---->||<----B---------->||<------C----->| Synchronous (multi-threaded):   thread A -> |<---A---->| \ thread B ------------> ->|<----B---------->| \ thread C ----------------------------------> ->|<------C----->|

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol