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

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


Thanks Jason!

I knew about JSR-133, but it still does not clarify if accessing a "final"
field or local variable is slower than a non-final field, for what ever
reasons... Does a final field/variable access incur additional cost?

Ashwin.


On Thu, Jan 15, 2009 at 2:11 PM, Jason T. Greene <jason.greene at redhat.com>wrote:

> 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<http://www.cs.umd.edu/%7Epugh/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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20090115/d5033a55/attachment-0001.html>


More information about the Concurrency-interest mailing list