Monday, 17 February 2014

AtomicInteger Java 7 vs Java 8

Atomic Integer is interesting class, it is used for building many lock free algorithm. Infact JDK locks are also build using ideas from Atomic datatypes.

As name suggest it is used for doing atomic increment/decremented, so you don't have to use locks, it will use processor level instruction to do so.
It is based on Compare-and-swap instruction.

Issue with CAS
CAS works on optimistic approach, it expects some failure, so it will retry operation, so in theory if there is no contention then it should work pretty fast.

There is another alternate way of doing same thing using Fetch-and-add.
Fetch-and-add is very different from CAS, it is not based on re-try loops.

Dave Dice compares CAS vs Fetch-and-add in atomic_fetch_and_add_vs blog, i can't explain better than this, so i will copy content from his blog


  1. CAS is "optimistic" and admits failure, whereas XADD does not. With XADD there's no explicit window of vulnerability to remote interference, and thus no need for a retry loop. Arguably, XADD has better progress properties, assuming the underlying XADD implementation doesn't have an implicit loop, but even in that case the window would be narrower than with Load;Φ;CAS.
  2. Lets say you were trying to increment a variable with the usual Load;INC;CAS loop. When the CAS starts failing with sufficient frequency you can find that the branch to exit the loop (normally taken under no or light contention) starts to predict toward the failure path. So when the CAS ultimately succeeds, you'll incur a branch mispredict, which can be quite painful on processors with deep pipelines and lots of out-of-order speculative machinery. Typically, this is in a piece of code where you don't want a long stall. There's no loop and no such issues with XADD.
Since fetch-and-add has predictable progress properties, so it is used for developing waiting free algorithms.
Unfortunately JDK 7 does not have support for fetch-and-add, one more reason why C++ people will be happy that C++ is great!


As we all know things do change & java community decided to added support for fetch-and-add in JDK8, one more good reason to migrate to JDK8.

In this blog i will compare performance of AtomicInteger from JDK7 & 8

Atomic Integer - JDK 7 vs JDK 8

In this test i increment counter 10 Million times with different number of threads. Thread numbers are increased to see how counter performs under contention.



X Axis - No of Threads
Y Axis - Ops/Second - Higher is better

JDK8 counter is winner in this case, best performance is when there is no contention , for JDK7 it is 80 MOPS but for JDK8 it close to 130 MOPS.
For single thread difference is not much , JDK8 is around 0.5 times faster but as contention increases performance JDK7 counter starts falling.

I will put another graph by removing 1 thread number, so that we can clearly see how these counter performs.


This gives better idea of how slow JDK7 atomic integer is, for 8 threads JDK8 counter is around 3.5X times faster.

Dive Into Code

JDK 8 - AtomicInteger
public final int getAndIncrement() {
        return unsafe.getAndAddInt(this, valueOffset, 1);
    }

JDK7 - AtomicInteger
 public final int getAndIncrement() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return current;
        }
    }

JDK8 is using new function(getAndAddInt) from unsafe to do the magic. Unsafe has become more useful!

Dive in Assembly
To just confirm that all performance again is coming from fetch-and-add i had look at assembly generated.

JDK 8 
0x0000000002cf49c7: mov    %rbp,0x10(%rsp)
  0x0000000002cf49cc: mov    $0x1,%eax
  0x0000000002cf49d1: lock xadd %eax,0xc(%rdx)  ;*invokevirtual getAndAddInt
                                                ; - java.util.concurrent.atomic.AtomicInteger::incrementAndGet@8 (line 186)


JDK 7

0x0000000002c207f5: lock cmpxchg %r8d,0xc(%rdx)
  0x0000000002c207fb: sete   %r11b
  0x0000000002c207ff: movzbl %r11b,%r11d        ;*invokevirtual compareAndSwapInt
                                                ; - java.util.concurrent.atomic.AtomicInteger::compareAndSet@9 (line 135)
                                                ; - java.util.concurrent.atomic.AtomicInteger::incrementAndGet@12 (line 206)

  
Conclusion
Introduction of fetch-and-add type of feature in java will make it more suitable for high performance computing, we will see more wait free algorithm in java

Code used for testing is available @ AtomicCounterTest
Just compile for jdk7/8 and execute it.

 Integer Java Class Example

121 comments:

  1. All your blogs are interesting and informative. Attaching code snippets is a great add on.

    ReplyDelete
  2. Good to hear that you find is useful.
    I do add link to GitHub that has code, I avoid adding code snippets to keep blog small, but try to include some in future post.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. According to wiki https://en.wikipedia.org/wiki/Fetch-and-add a consensus number is equal to 2. My understanding of that fact is that only up to 2 threads can act on a shared AtomicInteger without some waiting/congestion.
    How would you explain significant drop in performance of fetch-and-add between 1 and 2 threads (and not between 2 and 3).
    Similarly, why fetch-and-add performance degradation while comparing 2 threads with 3 threads is of same magnitude as when comparing 3 and 4 threads?

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. I checked unsafe.getAndAddInt implementation in Java 8 and it is still using compareAndSwap:
    public final int getAndAddInt(Object var1, long var2, int var4) {
    int var5;
    do {
    var5 = this.getIntVolatile(var1, var2);
    } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

    return var5;
    }

    I'm not sure where you're taking the information about the fetch and add

    ReplyDelete
    Replies
    1. I wrote short blog post to answer this question.
      http://ashkrit.blogspot.com/2017/07/java-intrinsic-magic.html

      Delete
  7. Super blog and very interesting information which I always wanted to search many article but you article is really fantastic.

    graphic designer in dubai

    ReplyDelete
  8. I’ve read several good stuff here. Definitely price bookmarking for revisiting. I wonder how a lot effort you put to create this sort of wonderful informative web site.
    Nadkaar - Dubai Website Design

    ReplyDelete
  9. Really informative and helpful blog. It gives a clear view of Java 7 and 8.
    SEO experts Dubai

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. good one, im waiting for more articlest like this. keep up the good work.
    SEO Dubai

    ReplyDelete
  12. This blog is really helpful regarding all educational knowledge I earned. It covered a great area of subject which can assist a lot of needy people. Everything mentioned here is clear and very useful.
    Content marketing montreal

    ReplyDelete
  13. Awesome post dude its so much informative for the followers and so much helpful also.I appreciate you for this great post.Thanks for sharing.Keep it up.

    Mobile App Development company Jordan | Digital Marketing Company Jordan | Blockchain Development Company in Jordan | Web Development Company in Jordan

    ReplyDelete
  14. Your blog is very informative and gracefully and your guideline is very good.Thank you
    Web Development Company in Bangalore, Ecommerce Website Development Company India

    ReplyDelete
  15. Thanks for sharing the great post.
    SMS is a great way of doing marketing. Many business giants are using text messaging to increase their sales.

    ReplyDelete
  16. I found this post interesting and worth reading. Keep going and putting efforts into good things.
    Yasir Jamal - Web design Dubai

    ReplyDelete
  17. I have been reading your blogs and I really started liking it.
    SEO Dubai

    ReplyDelete
  18. This is really interesting post,Appreciate the effort in educating us. We do provide
    Web Design Company in Bangalore

    ReplyDelete
  19. Hey Thanks for sharing this valuable information with us. I will come back to your site and keep sharing this information with us.pandaexpress.com/feedback

    ReplyDelete
  20. Hi,

    Thanks for sharing a very interesting article about AtomicInteger Java 7 vs Java 8. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    Regards,
    WondersMind,
    Best Website Design Company in Bangalore

    ReplyDelete

  21. ACME SURVEY
    : Step by Step Guide to take ACME customer satisfaction survey. Enjoy free coupons which can allow you to buy free things on next visit.
    Ready to win rewards? The latest & Updated Step by Step Guide for ACME survey online

    ReplyDelete
  22. Hey I loved the way you shared the valuable information with the community. I would say that please continue these efforts and we want to hear more from you.pandaexpress.com/feedbacktalktowendys

    ReplyDelete
  23. To find the best short term rentals in dubai i will suggest you to visit the MEX Short Term Rentals Dubai office if you're looking to plan you vacations soon in Dubai.

    ReplyDelete
  24. Thanks for sharing your ideas. I was desperately waiting for such posts. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.Seo Expert in Pakistan

    ReplyDelete
  25. It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks
    getmyoffersguide.com

    ReplyDelete
  26. Πολύ μεγάλο άρθρο. Σας ευχαριστώ. Μπορεί όλα τα καλά πράγματα να έρχονται σε σας. Αντίο

    Bồn ngâm massage chân

    Bồn ngâm chân

    Có nên dùng bồn ngâm chân

    Cách sử dụng bồn ngâm chân

    ReplyDelete
  27. Nice post!Everything about the future(giá nhà khung thép) is uncertain, but one thing is certain: God has set tomorrow for all of us(tấm bê tông siêu nhẹ). We must now trust him and in this regard, you must be(chi phí xây dựng nhà khung thép) very patient.

    ReplyDelete
  28. Hey Thanks for sharing this valuable information with us. I will come back to your site and keep sharing this information with us.
    Captions
    captions
    Captions
    captions

    ReplyDelete
  29. Amazing website. Great information provided. Learned a lot. Thank you
    https://platinumoffersonline.com/

    ReplyDelete
  30. Lets state you were attempting to increase a variable with the typical Load;INC;CAS circle. At the point when the CAS begins falling flat with adequate recurrence you can find that the branch to leave the circle (ordinarily taken under no or light conflict) begins to anticipate toward the disappointment way. So when the CAS at sareen air last succeeds, you'll bring about a branch mispredict, which can be very difficult on processors with profound pipelines and bunches of out-of-request theoretical apparatus. Ordinarily, this is in a bit of code where you don't need a long slow down. There's no circle and no such issues with XADD.

    ReplyDelete
  31. What an amazing post you written really love the post please do tell me how to subscribe your blog as and one more thing visit https://kroger-feedback-survey.com/ and win free $5000 gift cards for Kroger grocery stores to shop for free.

    ReplyDelete
  32. ඔබේ කාර්යය සෑම විටම හොඳයි, වඩාත් රසවත් ලිපි තිබිය යුතුය.

    cần mua chó Poodle

    cách nuôi chó Poodle

    đặc điểm chó Poodle

    Nguồn gốc chó Poodle

    ReplyDelete
  33. Hi blogger, i must say you have hi quality articles here.
    Your website can go viral. You need initial traffic boost only.
    How to get it? Search for; make your content go viral Wrastain’s tools
    web application development company in India | ecommerce web development

    ReplyDelete
  34. នេះគឺជាផ្នែកមួយនៃអត្ថបទដ៏ត្រជាក់បំផុតនៃសតវត្សទី។ សូមអរគុណចំពោះការចែករំលែក។ សូមជូនពរអ្នកអោយមានសំណាងនិងជោគជ័យ!

    C.ty bán cửa lưới tại huyện Đông Anh

    Đại lý cửa lưới chống muỗi tại Quảng Ninh

    Siêu thị cửa lưới chống muỗi tại Linh Đàm

    Siêu thị bán cửa chống muỗi phường Phương Mai

    ReplyDelete
  35. Ցանկանում եմ շնորհակալություն հայտնել ձեզ: Շատ հետաքրքիր եւ հետաքրքիր հոդված ստեղծելու համար: Good luck

    lều xông hơi loại nào tốt

    lều xông hơi cá nhân

    bán lều xông hơi

    mua lều xông hơi ở đâu

    ReplyDelete
  36. GCC web hosting is a leading web hosting and domain registrar in the heart of UAE, Dubai.

    ReplyDelete
  37. Wonderful blog post. I was viewing continuously this website and I am satisfied! Highly beneficial information particularly the last part. I take care of this kind of information much. I was seeking this specific information for a long time. Thanks and good luck.
    Management your google Ads

    ReplyDelete
  38. It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks
    https://myinstantofferonline.com/
    https://www.peryourhealthonline.com/
    https://www.myindigocardoffer.com/

    ReplyDelete
  39. Nice.

    Freshpani is providing online water delivery service currently in BTM, Bangalore you can find more details at Freshpani.com
    Online Water Delivery | Bangalore Drinking Water Home Delivery Service | Packaged Drinking Water | Bottled Water Supplier

    ReplyDelete
  40. ನಿಮ್ಮ ಕುಟುಂಬ ಮತ್ತು ಪ್ರೀತಿಪಾತ್ರರ ಜೊತೆ ನಿಮಗೆ ಹೊಸ ಮತ್ತು ಸಂತೋಷದ ಹೊಸ ವಾರ ಶುಭಾಶಯಗಳು. ಲೇಖನವನ್ನು ಹಂಚಿಕೊಂಡಿದ್ದಕ್ಕಾಗಿ ಧನ್ಯವಾದಗಳು

    lều xông hơi mini

    mua lều xông hơi ở đâu

    lều xông hơi gia đình

    bán lều xông hơi

    xông hơi hồng ngoại

    ReplyDelete
  41. Një artikull shumë interesant dhe interesant. Faleminderit për ndarjen

    Phụ kiện tủ bếp
    Phụ kiện tủ bếp cao cấp

    ReplyDelete
  42. "I loved the post, keep posting interesting posts. I will be a regular reader...

    hairclinic.pk

    ReplyDelete
  43. Hey, I loved the way you shared the valuable information with the community. I would say that please continue these efforts and we want to hear more from you.
    HamzaAndHamzaTaxReturns

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. This is a decent post. This post gives genuinely quality data. I'm certainly going to investigate it. Actually quite valuable tips are given here. Much obliged to you to such an extent. Keep doing awesome. To know more information about
    Contact us :- https://www.login4ites.com/

    ReplyDelete
  46. It is brilliant substance. I for the most part visit numerous locales however your site has something unique highlights. I for the most part visit on your site. Best Seo Tips
    Contact us- https://myseokhazana.com

    ReplyDelete
  47. "I loved the post, keep posting interesting posts. I will be a regular reader...

    hairclinic.pk

    ReplyDelete
  48. """I loved the post, keep posting interesting posts. I will be a regular reader...

    hairclinic.pk

    ReplyDelete
  49. "I loved the post, keep posting interesting posts. I will be a regular reader...

    hairclinic.pk"

    ReplyDelete
  50. "I loved the post, keep posting interesting posts. I will be a regular reader...

    hair transplant pakistan

    ReplyDelete
  51. """I loved the post, keep posting interesting posts. I will be a regular reader...

    hair transplant pakistan

    ReplyDelete
  52. "I loved the post, keep posting interesting posts. I will be a regular reader...

    hair transplant in pakistan

    ReplyDelete
  53. I loved the post, keep posting interesting posts. I will be a regular reader...

    Rent a car from Saifal Muluk lake

    ReplyDelete
  54. "I loved the post, keep posting interesting posts. I will be a regular reader...

    Rent a car from Islamabad to Skardu

    ReplyDelete
  55. "I loved the post, keep posting interesting posts. I will be a regular reader...

    Rent a car from Islamabad to Kashgar

    ReplyDelete
  56. I loved the post, keep posting interesting posts. I will be a regular reader...

    Rent a car from Islamabad to Kashmir tour

    ReplyDelete
  57. I loved the post, keep posting interesting posts. I will be a regular reader...

    SEO Company London

    ReplyDelete
  58. "I loved the post, keep posting interesting posts. I will be a regular reader...

    yourcar.pk

    ReplyDelete
  59. "I loved the post, keep posting interesting posts. I will be a regular reader...

    rent a car islamabad without driver

    ReplyDelete
  60. "I loved the post, keep posting interesting posts. I will be a regular reader...

    SeoMagician.co.uk

    ReplyDelete
  61. "I loved the post, keep posting interesting posts. I will be a regular reader...

    seomagician.co.uk

    ReplyDelete
  62. I loved the post, keep posting interesting posts. I will be a regular reader


    https://talkwithstranger.com/

    ReplyDelete
  63. Pretty nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your blog posts. After all, I’ll be subscribing to your feed and I hope you write again soon!

    Sunglasses price in Pakistan

    ReplyDelete
  64. Thanks for sharing this information. In my opinion, JDK8 counter is winner in this case, i would say best performance is when there is no contention.
    Pls Xpectations

    ReplyDelete
  65. Really it is a very nice topic and Very significant Information for us, I have think the representation of this Information is actually super one. . new metro city saraialamgir loction

    ReplyDelete
  66. Really it is a very nice topic and Very significant Information for us, I have think the representation of this Information is actually super one. . SEO Services Monthly

    ReplyDelete
  67. It so good idea so i appreciate it and its a good thingstore of generators

    ReplyDelete
  68. i think it is very best thing and it s better for us so visit itNo.1 monthly seo services

    ReplyDelete
  69. I think it is so good thing so it is very useful forn you Monthly Seo Servic

    ReplyDelete
  70. Appreciating the hard work you put into your site and detailed information you offer. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed materialSDMO generators

    ReplyDelete
  71. its really great information Thanks For sharing new metro city

    ReplyDelete
  72. its really great information Thanks For sharing new metro city

    ReplyDelete
  73. Amazing it is a very helpful topic and Very significant Information for us, thanks for sharing new metro city

    ReplyDelete
  74. Very nice article, very informative and provides alot of insight of the project. new metro city

    ReplyDelete
  75. I have recently started a blog, the info you provide on this site has helped me greatly in blogging. Thanks for all of your work and time Lookfantastic copoun

    ReplyDelete
  76. your article so good, but more search on this topic. new metro city

    ReplyDelete
  77. Great Article, i was really confused about this but because of the information provided i can easily make a decision now.new metro city

    ReplyDelete
  78. Nice information. Thanks for sharing such an amazing article. For Latest News and updates please visit our website: TV9 Marathi Media News

    ReplyDelete
  79. This blog is useful as well as informative. Keep sharing such blogs I really like your posts Wireless Bluetooth Earbud

    ReplyDelete
  80. This blog is useful as well as informative. Keep sharing such blogs I really like your postsAwok Coupon code

    ReplyDelete
  81. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    tell the bell

    ReplyDelete
  82. I learn some new stuff from it too, thanks for your information.
    Kroger feedback survey

    ReplyDelete
  83. Very Informative topic I liked it very much. You have covered the topic in detail thumbs up. Economy Tarpaulin

    ReplyDelete
  84. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed materialRoofing NYC

    ReplyDelete
  85. This blog is useful as well as informative. Keep sharing such blogs I really like your postsAccounting software

    ReplyDelete
  86. This blog is useful as well as informative. Keep sharing such blogs I really like your postsinfluencer marketing agency

    ReplyDelete