[concurrency-interest] AtomicInteger implementation

Yann Le Tallec ylt at letallec.org
Thu Feb 28 17:15:24 EST 2013


I see. On JDK 7u11, running with PrintAssembly on, it looks like the JIT
does compile the code as is (possibly not treated as an intrinsic method in
that version?). As you explained:
- incementAndGet translates into an INC
- addAndGet translates into an ADD,1.

However, according to Intel optimisation guidelines for x86, ADD,1 can be
faster than INC. A quick and dirty micro benchmark actually shows that
addAndGet(1) is fairly consistently 2-5% faster than incrementAndGet (intel
i5 - 64bit) post JIT compilation.

Hence the question ;-)


On 28 February 2013 21:53, Nathan Reynolds <nathan.reynolds at oracle.com>wrote:

>  Good question.
>
> For Hotspot x86, it doesn't matter.  HotSpot has intrinsics for these
> methods.  So, on x86 they compile down to a single atomic instruction.
>
> For weaker JITs, increment by 1 can be much faster since it is a constant
> and there can be an instruction on the processor for incrementing.  This
> statement assumes that addAndGet(1) wouldn't be inlined.
>
> Nathan Reynolds<http://psr.us.oracle.com/wiki/index.php/User:Nathan_Reynolds>| Architect |
> 602.333.9091
> Oracle PSR Engineering <http://psr.us.oracle.com/> | Server Technology
>  On 2/28/2013 2:29 PM, Yann Le Tallec wrote:
>
> Hello,
>
> all the code of incrementAndGet (in JDK 7) but one line is identical to
> addAndGet.
> What is the reason why the code has been duplicated instead of
> implementing incrementAndGet as:
>
> public final int incrementAndGet() {
>     return addAndGet(1);}
>
> Regards,
> Yann
>
> -----
>
>  For reference, the two methods:
>
> public final int addAndGet(int delta) {
>     for (;;) {
>         int current = get();
>         int next = current + delta;         // Only difference
>         if (compareAndSet(current, next))
>             return next;
>     }}
> public final int incrementAndGet() {
>     for (;;) {
>         int current = get();
>         int next = current + 1;             // Only difference
>         if (compareAndSet(current, next))
>             return next;
>     }}
>
>
>
> _______________________________________________
> Concurrency-interest mailing listConcurrency-interest at cs.oswego.eduhttp://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20130228/d1a6a7eb/attachment.html>


More information about the Concurrency-interest mailing list