[concurrency-interest] AtomicInteger implementation

Nathan Reynolds nathan.reynolds at oracle.com
Thu Feb 28 16:53:18 EST 2013


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);
> }
> |
> |R|egards,
> 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 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/2b22f14a/attachment.html>


More information about the Concurrency-interest mailing list