This post is part of the third session of the Nuggets Creators Training Camp.Digg project | Creator Boot Camp phase 3 is underway, “write” to make a personal impact.
π preface
From my comment on the article of a bigwigs I admire:
I: “drink the water of the Yellow River to the sky, wine to wake up the willow moon and steal huan, sing a smile the proud river’s lake offering the sea, wild goose across the cold pool have a few back”
Big guy: “young just, longitudinal code fly cheng, slightly jiangshan Hua Yue, there are a few people along with fu θθΈιΎη.”
π get down to business
Threads or locks play a role in concurrent programming similar to rivets and I-beams play a role in civil engineering. To build a strong bridge, a large number of rivets and I-beams must be used correctly. Similarly, threads and locks must be used correctly when building robust concurrent programs. But these are just mechanics. At the heart of writing thread-safe code is the management of state access, especially to Shared and Mutable states.
-
Object state: Refers to data stored in state variables, but may also contain other fields that depend on objects.
- For example, a certain
HashMap
The state is not only stored inHashMap
The object itself is also stored in manyMap.Entry
In the object. The state of an object contains any data that may affect its externally visible behavior.
- For example, a certain
-
Shared: Shared means that a variable can be accessed by multiple threads at the same time.
-
Mutable: Means that the value of a variable can change over its lifetime.
Note: A discussion of thread safety should focus more on preventing uncontrolled concurrent access to data. Whether an object needs to be thread-safe depends on whether it is accessed by multiple threads. (Refers to how an object is accessed in a program, not what it is intended to do.)
When multiple threads access a state variable and one thread writes to it, synchronization must be used to coordinate their access to the variable.
- Keyword synchronized: provides an exclusive locking mode.
- Voatile type variables: Synchronization should also include Explicit locks and atomic variables.
If one of the synchronization mechanisms is ignored, it may cause an error when multiple threads access the same mutable state variable without using the appropriate synchronization. Fix:
-
This state variable is not shared between threads
-
Change a state variable to an immutable variable
-
Use synchronization when accessing state variables
Note: When designing thread-safe classes, good object-oriented techniques, immutability, and clear immutable specifications can help.
When writing concurrent applications, the correct programming approach is to first make the code work correctly and then speed it up. Even then, it’s best to optimize only when performance testing and application requirements tell you that you need to improve performance, and when measurements show that the optimization will actually improve performance in the real world.
π What is thread safety
We all know that the more formal the definition, the more complex it is, and not only difficult to provide guidance from practical meaning, but also difficult to understand intuitively. There are many online definitions, such as:
-
Can be called in multiple threads without error interaction between threads.
-
Can be called by multiple threads at the same time without requiring the caller to perform additional action.
No wonder we get confused about thread-safety, because it sounds like “if a class can be used safely across multiple threads, it’s a thread-safe class.” Although there is not a lot of controversy, but what practical significance and help?
What does “safe” mean?
- In the definition of thread safety, the most central concept is correctness.
- The correct meaning is that a class behaves exactly as its specification does
I define the correctness approximation of single threads as “what you see is what you know”. After giving a clear definition of correctness, thread safety can be defined:
-
A class is said to be thread-safe if it consistently behaves correctly when accessed by multiple threads.
-
A class is called thread-safe when it is accessed by multiple threads and behaves correctly, regardless of how the criminal environment is scheduled or how the threads will execute interchangeably, and without any additional synchronization or coordination in the calling code.
-
Since single-threaded programs can also be considered multithreaded programs, if a class is not correct in a single-threaded environment, it is certainly not thread-safe (that is, a program must work correctly in the first place).
β¨ Simple example
Often, the need for thread-safety comes not from direct use of counties, but from using imagesServlet
Such frameworks (and there are many more).
A servlet-based factorization service that gradually extends functionality and ensures its thread-safety.
A stateless Servlet:
@ThreadSafe
public class StatelessFactorizer implements Servlet {
public void service(ServletRequest req,ServletResponse resp) {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = factor(i);
encodeIntoResponse(resp,factors);
}
}
Copy the code
Like most servlets, StatelessFactorizer is stateless and contains neither any fields nor any references to fields in other classes. The temporary state during the calculation exists only in local variables on the thread stack and can only be accessed by the executing thread. One thread accessing the StatelessFactorizer does not affect the results of another thread accessing the same StatelessFactorizer, because the two threads do not share state, as if they were accessing different instances. Stateless objects are thread-safe because the behavior of a thread accessing a stateless object does not affect the correctness of operations in other threads.
-
Stateless objects must be thread-safe.
-
Most of the
Servlet
Are stateless, thus greatly reducing the implementationServlet
Complexity in thread safety. Only when theServlet
Thread safety becomes an issue when some information needs to be saved while processing requests.
π finally
-
Next we’ll cover the basics of Concurrent Programming in Java: Atomicity for thread safety
-
For more references, see here:The Blog of Chan Wing Kai
-
Like the small partner of the blogger can add a concern, a thumbs-up oh, continue to update hey hey!