One, what is thread-safe
The thread-safe topic we're talking about is based on the premise that a variable will be accessed by multiple threads, which is not a problem if it's just a single-threaded application.
A variable is accessed by multiple threads we call this variable shared. While a variable can be modified in its lifecycle, it is called variable. There are a lot of people on the web trying to define thread safety, many of them anyway, but ultimately the core point of thread safety is correctness . Imagine that when multiple threads access a shared variable, the goal is to get the right data.
Here's my understanding of thread safety: If an object is accessed by more than one thread, if each thread can get the correct value for the read operation of the object, and the write operation of the object can be safely written (it will not overwrite the previously written data and the data being written conforms to the specification of the Class), The simple thing is that the class behaves correctly, and the class is thread-safe. Thread-Safe class customers can be used under any circumstances, of course, if it is single-threaded, it is best not to use, because the thread-safe classes are encapsulated in the necessary synchronization, and synchronization design to the lock, lock overhead is relatively large, a single thread may affect its performance.
I don't know if you've heard of stateless classes, a stateless class is worth being a class with no member variables, no reference to other variables, or a member variable that is immutable, or a member variable that is a single instance, such as a struts1 action, can be a single case, because he is stateless. The values in stateless classes (which may be computed or, possibly, when arguments are passed in) are uniquely present in local variables, which are stored on the thread's stack and are accessible only by the executing thread.
public class Statelessservlet implements servlet{public
void service (ServletRequest Req,servletresponse resp) {
BigInteger i=extractfromrequest (req);
Biginteger[] Factors=factor (i);
Encodeintoresponse (resp,factors);
}
As I obtained from the request in the code above, the factors is computed and the servlet is stateless. We can conclude that stateless classes are thread-safe . Second, the atomic Nature
We modify the code above, plus a count variable
public class Statelessservlet implements servlet{
private long count=0;
public void Service (ServletRequest Req,servletresponse resp) {
BigInteger i=extractfromrequest (req);
Biginteger[] Factors=factor (i);
count++;
Encodeintoresponse (resp,factors);
}
There seems to be nothing wrong with this code, but here the count++ is not atomic, it includes three steps, "read-Change-write", so there may be cases where AB two threads access this method at the same time, AB two threads see the value of Count 9, Then all of them are added 1 and finally 10 causes a count to vanish in a vacuum.
Why is this happening? Because of the competitive conditions in this period, the results are unreliable. When the correctness of the calculation depends on the timing of the running clock or the alternation of multithreading, the competition condition is generated. In other words, to get the right answer depends on the "lucky timing." One of the most common competitive conditions is "check and run Again", using a potential expiration value as a basis for deciding what to do next.
Just like the lazy type in the single design pattern we know, this is the competitive condition.
Class lazysingleton{
Private Lazysingleton () {}
private static Lazysingleton lazysingleton=null;
This is a thread-insecure public
static Lazysingleton getinstance () {
if (lazysingleton==null) {return
new Lazysingleton ();
}
Return Lazysingleton
}
}
We'll call it a composite operation, like count++, if the composite operation is performed all at once or not at all, it can be called atomic operation III, Lock (Synchronized)
How to turn a composite operation into atomic operation, using the Synchronized keyword can be done. Java provides a built-in lock mechanism for enforcing atomicity: synchronized blocks. A synchronized block has two parts: a reference to the lock object, and a block of code for this lock protection. Lock-protected blocks of code can guarantee that the operation inside is atomic.
Synchronized (lock) {
//access or modify the shared state of the chained report
}
Each Java object can implicitly play the role of a lock used for synchronization, and these built-in locks are called internal or monitor locks. The lock is automatically acquired before the execution thread enters the synchronized block, and the thread discards the acquired lock, whether the normal exit or the exception is thrown. The same internal lock can only be acquired by one thread at a time, so the internal lock also plays a mutex role in Java. It is precisely because of this mechanism that synchronized can guarantee that the code block inside can only be executed by one thread at a time, thus guaranteeing the atomicity of its composite operation.
The internal lock also has a feature called re-enter . Re-entry means that when a thread attempts to acquire its own lock, the request succeeds and also means that the request for the lock is based on "per-thread" rather than "per-call." The re-enter implementation is by associating a request count for each lock and a thread that occupies it. When the count is 0 o'clock, the lock is considered to be not occupied. When a thread requests an unlocked lock, the JVM records the possessor of the lock and resets the request count to 1. If the same thread requests this lock again, the counter increments, each time the thread exits the sync block, the counter minus one. The lock is released until the counter is 0.
public class widget{public
synchronized void dosomething () {
...
}
} public class Loggingwidget extends widget{public
synchronized void dosomething () {
super.dosomething ();
}
}
If the internal lock cannot be entered again, the code is locked.
For each variable state variable that can be accessed by multiple threads, if all the threads accessing it occupy the same lock in execution, we call this variable protected by this lock.
When using synchronized, you should know how to protect the blocks of code, not too big or too small. Too big, such as the entire service in the servlet package up, although it is safe, but contrary to the original intent of the container design, so that a request to come over can only one treatment, and too small may be the composite operation to take apart, so use the time to conduct a reasonable analysis. There are also time-consuming operations such as requesting network resources, IO operations, and so on, so as not to occupy the lock