Solved

what is volatile and atomic in java

Posted on 2014-12-17
8
87 Views
Last Modified: 2015-01-03
Hi,
I want to know the meaning of atomic and volatile variables in java. When to declare a variable volatile or atomic?

I have the following variable in my code -
    private boolean _verificationInProgress = false;
should i make it atomic or voltaile and why ?

This variable is inside a class whose instance is only created once during the lifecycle of an application and used elsewhere.
Thanks
0
Comment
Question by:Rohit Bajaj
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 40505061
Have you read the lit on this? The API doc is actually quite good at explaining the similarities and wider functions of the atomic kit. Look here.
0
 
LVL 26

Accepted Solution

by:
dpearson earned 400 total points
ID: 40505149
When to declare a variable volatile or atomic?
Volatile and Atomic are both very similar in what they do.  In general, these days you should prefer Atomic like this:

private AtomicBoolean _verificationInProgress = new AtomicBoolean(false) ;

Atomics are newer additions to the language and offer more operations than volatile variables do (e.g. atomic gets and sets).

Now the question is - when do you need either volatile or atomic?

The answer to that is when the variable is shared between multiple threads.  If you are going to be updating or reading this variable from more than 1 thread, then you should make it atomic.

Doug
0
 

Author Comment

by:Rohit Bajaj
ID: 40506173
Hi,
I read the following example for volatile -
volatile boolean stop = false;
void loop() {
    while (!stop) { ... }
}
void stop() { stop = true; }
If you have a thread running loop() and another thread calling stop(), you might run into an infinite loop if you omit "volatile", since the first thread might cache the value of stop

Here i dont understand how will the thread get into infinite loop. As after the value of stop gets updated why will it not get reflected to the other thread. I think it may not be immediate but still it will be less than a fraction of second even if we dont declare the variable as volatile.
Also how does a thread in java caches variables ?
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40508602
As after the value of stop gets updated why will it not get reflected to the other thread?

This is actually a pretty subtle feature in the way threads work.  The problem is that there can be 2 CPUs, each running a different thread.  If you don't tell the compiler that the "stop" variable needs to be shared between the threads, then each thread is allowed to keep the "stop" variable in its local processor cache as long as it wishes (which could be for minutes for a tight loop).

It does NOT need to send that value back to the main memory.

So since the value is stored in the local processor cache, the 2nd thread cannot see it (since each processor has its own cache).  This sort of bug literally will not happen if you run it on a machine with a single CPU.  It can only show up on a machine with multiple CPUs (or at least multiple cores).

If you use "synchronize" or "volatile" or "AtomcBoolean" - all of them tell the compiler "this variable is shared between threads" and now when its value changes that value WILL ALWAYS be sent back to main memory - making it visible to all other threads.

Does that make sense?

It's pretty complicated.

Doug
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 16

Expert Comment

by:krakatoa
ID: 40508824
I don't know (but do care) what Doug might have on this take, but my "sketch" would be that 'volatile' is more akin to a superstatic variable if you see what I mean - IOW one that is practically shared amongst threads, but protected at the same time. With 'volatile' you can prescribe protected treatment of primitives, which otherwise is more convoluted to achieve.

java.util.concurrent.atomic and friends is more angled to the access and implementation of protection, so it's more of a way of validating access and ensuring consistency, rather than personal variable bodyguarding, if that makes any sense. So volatile - var wears a body vest. Atomic, entourage shoots the assassin.
0
 

Author Comment

by:Rohit Bajaj
ID: 40508877
HI,
Even if there is a single CPU. Each thread can keep its local copy and use it. I think this way also there can be possibility of infinite loop ?
0
 
LVL 14

Assisted Solution

by:CPColin
CPColin earned 100 total points
ID: 40509545
Not infinite, just longer than you meant it to go.
0
 
LVL 26

Expert Comment

by:dpearson
ID: 40510222
Even if there is a single CPU. Each thread can keep its local copy and use it.

If there's a single CPU, then when we context switch between the threads,  the local cache will be cleared (at least that's my understanding of how the processor cache works - it could be wrong and/or processor architecture specific).  If the cache is cleared, then the next time the cache is loaded (from main memory), the other thread will see the correct value.

So on a single CPU machine the longest wait would be the time until the next context switch - which is maybe a few milliseconds if we have 2 threads ready to run.  If one of the threads is blocked, then I guess this could be an arbitrary wait.  But on a machine with 2 CPUs (or 16 CPUs), if there are only 2 threads, you could be waiting for a long time before that next context switch happens because each thread gets its own CPU and there's no need for a context switch.

The take home of all this is:

    To write correct multi-threaded code, any variable that is shared between 2 threads MUST use some sort of concurrent indicator (volatile, synchronized, Atomic...) for the code to work correctly in all situations.

Without this you violate the Java memory model and Java is allowed to produce fast, but incorrect code.

Doug
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now