[concurrency-interest] Clarification: volatile, final and atomic ops

Jason T. Greene jason.greene at redhat.com
Thu Jan 15 17:11:33 EST 2009


Ashwin Jayaprakash wrote:
> Hello,
> I'm seeking some clarification with regards to volatile, final and 
> atomic ops.
> 
> I have pasted some really simple Java code that performs work in a loop 
> below. Every 1024 times, it updates an AtomicInteger with the results it 
> has accumulated so far.
> 
> I'd like to know if the access to the AtomicInteger which touches a 
> volatile field inside affects the loop all the other times the if(..) 
> block is not executed. I tried printing the Assembly using JDK7 and 
> couldn't really figure out anything from the output. So, even if the 
> volatile field is accessed only once every 1024 times, does the program 
> issue a fence (right term?) instruction all the time? 

No they are issued only when the field is accessed.

? If it does, then
> how do I avoid those expensive volatile fields accesses?
> 
> What is the scope of the happens-before/after ordering that the VM 
> ensures? Is it restricted to field accesses and sync blocks within a 
> method or the program's entire instruction stream?

Thats a long answer. I would start here:
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html

> Program:
> 
> public class Temp {
>     static final AtomicInteger STEP1_TOTAL = new AtomicInteger();
> 
>     static void test() {
>         int localTotal = 0;
>         
>         for (int i = 0; i < 1000* 1024; i++) {
>             localTotal += doComplexWorkStep1();
> 
>             if ((i & 1023) == 0) {
>                 STEP1_TOTAL.addAndGet(localTotal);
>                 localTotal = 0;
>             }
> 
>             doComplexWorkStep2();
>         }
>     }
> 
>     static int doComplexWorkStep1() {
>         return 100;
>     }
> 
>     static void doComplexWorkStep2() {
>     }
> 
>     public static void main(String[] args) {
>         test();
>     }
> }
> 
> Also, how does using "final" for a Local Variable affect performance? Is 
> it just a compiler thing or does it also result in volatile-like access? 
> How about "final" for Fields?

See above FAQ

-- 
Jason T. Greene
JBoss, a division of Red Hat


More information about the Concurrency-interest mailing list