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

Ashwin Jayaprakash ashwin.jayaprakash at gmail.com
Thu Jan 15 16:16:18 EST 2009


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? 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?

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?

Thanks and apologies for asking such dumb questions.

Ashwin.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20090115/dabfece9/attachment.html>


More information about the Concurrency-interest mailing list