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

Joe Bowbeer joe.bowbeer at gmail.com
Thu Jan 15 16:44:03 EST 2009


The cost of atomic addAndGet depends on the VM implementation and the
underlying platform.  It may even depend on what other threads are doing.
The cost might be lower when there is low contention and higher when then is
high contention.  If the compiler (read "VM") can determine that there is no
contention, there may be no cost.  I try not to think about it too much.

What I can say definitively is that your code only pays the price when
addAndGet is invoked.  That is, once every 1024 iterations.

Concerning final, that's a compiler thing.

Joe

On Thu, Jan 15, 2009 at 1:16 PM, 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? 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/8eea4499/attachment.html>


More information about the Concurrency-interest mailing list