In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge about whether it is better to use LongAdder or volatile. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
[reference] volatile solves the invisible problem of multithreaded memory. For write-and-read, you can solve the problem of variable synchronization, but if you write more, you can't solve the problem of thread safety.
Note: if it is a count++ operation, use the following classes: AtomicInteger count = new AtomicInteger (); count.addAndGet (1); for JDK8, it is recommended to use LongAdder object, which has better performance than AtomicLong (reducing the number of retries for optimistic locks).
There are two key points in the above content:
Volatile cannot be used in non-write-and-read scenarios like count++.
If it is JDK8, it is recommended to use LongAdder instead of AtomicLong instead of volatile, because LongAdder has better performance.
But there is no evidence, even if it is the lonely boss said, we have to prove it, because Grandpa Ma said: practice is the only criterion for testing truth.
This also has its advantages: first, it deepens our understanding of knowledge; second, the document only says that the performance of LongAdder is better than AtomicLong, but how much higher? It is not said in the article that we have to test it ourselves.
(recommended tutorial: Java tutorial)
Without much to say, let's go straight to the official content of this article.
Volatile thread safety testing
First, let's test the thread safety of volatile in a multi-write environment. The test code is as follows:
Public class VolatileExample {public static volatile int count = 0; / / counter public static final int size = 1000000; / / number of cyclic tests public static void main (String [] args) {/ / + + 10w Thread thread = new Thread (()-> {for (int I = 1; I)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.