In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 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 points about how to achieve thread safety in Java concurrent programming. 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.
1. What is thread safety?
When multiple threads access a class, regardless of how the runtime environment invokes or how these threads will be executed alternately, and does not require any additional synchronization or coordination in the tone code, the class behaves correctly, so the class is called thread-safe.
Stateless objects must be thread-safe, such as Servlet.
two。 Atomicity 2.1 competitive conditions
The situation where incorrect results occur as a result of inappropriate timing is the condition of competition.
The "check first and then execute" operation determines the next action through a potentially effective observation. For example: delayed initialization.
If (instance = = null) {instance = new SomeObject ();}
The result state of the read-modify-write operation depends on the previous state. Such as: incremental operation.
Long count = 0security countdown 2.2 compound operation
An atomic operation means that for all operations (including the operation itself) that access the same state, the operation is performed as an atomic (indivisible) operation.
To ensure thread safety, it contains a set of operations that must be performed atomically, called composite operations.
Incremental operations can use an existing thread-safe class to ensure thread safety. Such as:
AtomicLong count = new AtomicLong (0); count.incrementAndGet (); 3. Locking mechanism
When a class has only one state variable, the thread safety of the class can be maintained through thread-safe state variables. But if the class has more state, you can't just add more thread-safe state variables. To maintain state consistency, all relevant state variables need to be updated in a single atomic operation.
3.1 built-in lock
Java provides a built-in lock: a synchronous code block, which includes an object reference as a lock and a code block protected by the lock.
A method decorated with the keyword synchronized is a synchronous code block that spans the entire method body, where the lock of the synchronous code block is the object on which the method call is located. Static synchronized methods take the Class object as the lock.
The thread automatically acquires the lock before entering the synchronous code block and automatically releases the lock when exiting the synchronous code block. At most one thread can hold such a lock, so the synchronization code is executed atomically.
3.2 re-entry
The built-in lock is reentrant, which means that the granularity of the operation that acquires the lock is a thread, not a call. The request also succeeds when a thread tries to acquire a lock that is already held by itself.
Reentry further improves the encapsulation of locking behavior and simplifies the development of object-oriented concurrent code.
Public class Widget {public synchronized void doSomething () {/ /. }} public class LoggingWidget extends Widget {public synchronized void doSomething () {/ /. Super.doSomething (); / / if there is no reentrant lock, this statement will result in a deadlock. }} 4. Protect the state with a lock
For a variable state variable that may be accessed by multiple threads at the same time, it is necessary to hold the same lock when accessing it. In this case, it is said that the state variable is protected by this lock.
5. Activity and performance
Coarse-grained use of locks ensures thread safety, but can cause performance and activity problems, such as:
@ ThreadSafepublic class SynchronizedFactorizer implements Servlet {@ GuardedBy ("this") private BigInteger lastNumber; @ GuardedBy ("this") private BigInteger [] lastFactors; public synchronized void service (ServletRequest req, ServletResponse resp) {BigInteger I = extractFromRequest (req); if (i.equals (lastNumber)) encodeIntoResponse (resp, lastFactors); else {BigInteger [] factors = factor (I) / / Factor decomposition calculation lastNumber = I; lastFactors = factors;// stores the last calculation result encodeIntoResponse (resp, factors);}
By shrinking the synchronization block, you can ensure the concurrency of servlet while maintaining thread safety. Instead of splitting what is supposed to be atomic operations into multiple synchronous code blocks, try to separate operations that do not affect the shared state and take a long time to execute from the synchronous code. Such as:
Public class CachedFactorizer implements Servlet {@ GuardedBy ("this") private BigInteger lastNumber; @ GuardedBy ("this") private BigInteger [] lastFactors; public void service (ServletRequest req, ServletResponse resp) {BigInteger I = extractFromRequest (req); BigInteger [] factors = null; synchronized (this) {if (i.equals (lastNumber)) {factors = lastFactors.clone () }} if (factors = = null) {factors = factor (I); synchronized (this) {lastNumber = I; lastFactors = factors.clone ();}} encodeIntoResponse (resp, factors) }} these are all the contents of the article "how to achieve thread safety in Java concurrent programming". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.