Thread Safety
The thread safety we are discussing here is limited to the premise that shared data access exists between multiple threads, because if a piece of code does not share data with another thread at all, then from a thread-safe point of view, there is no difference in whether the program is serially executed or multithreaded.
Shared data
The data shared by various operations in the Java language can be divided into the following 5 classes: immutable, absolute thread-safe, relative thread-safe, thread-compatible, and thread-antagonistic.
Not variable
Immutable (immutable) objects must be thread-safe, regardless of the method implementation of the object or the caller of the method, no need to take any further thread safety measures, the final keyword brings visibility, As long as an immutable object is constructed correctly (without the case of this reference escaping), the visible state of the external is never changed and will never be seen in an inconsistent state in multiple threads. The "immutable" security is the simplest and purest.
In the Java language, if the shared data is a basic data type, it is guaranteed to be immutable as long as it is decorated with the final keyword when defined. If the shared data is an object, it is necessary to ensure that the behavior of the object does not have any effect on its state, you can think of the object of the Java.lang.String class, it is a typical immutable object, we call its substring (), Replace () and concat () None of these methods will affect its original value, only a newly constructed string object will be returned.
There are many ways to ensure that object behavior does not affect your state, the simplest of which is to declare the variable with state in the object as final, so that after the constructor ends, it is immutable, For example, as shown in the Java.lang.Integer constructor, it guarantees that the state is the same by defining the internal state variable value as final.
/*** The value of the {@codeInteger}. * * @serial */ Private Final intvalue; /*** Constructs a newly allocated {@codeInteger} object that * represents the specified {@codeint} value. * * @paramValue the value to being represented by the * {@codeInteger} object. */ PublicInteger (intvalue) { This. Value =value; }
Types that conform to the immutable requirements in the Java API, in addition to the string mentioned above, are commonly used for enumeration types, As well as partial subclasses of Java.lang.Number, such as long and double numeric wrapper types, large data types such as BigInteger and BigDecimal, but atomic classes Atomicinteger and Atomiclong for subtypes of number are not immutable, Readers may wish to look at the source code of these two atomic classes and think about why.
Absolute thread Safety
A class to achieve "regardless of the runtime environment, the caller does not need any additional synchronization measures," often need to pay a great, even sometimes unrealistic costs. Labeling yourself as a thread-safe class in the Java API, most of which is not an absolute thread-safe. We can see what "absolute" means here by using a thread-safe class that is not "absolutely thread safe" in the Java API.
If Java.util.Vector is a thread-safe container, I believe all Java programmers will have no objection to this, because its add (), get () and size () methods are synchronized decorated, although this is very inefficient, But it's really safe. However, even if all of its methods are modified to synchronize, it does not mean that the time to invoke it will never be synchronized.
Thread Removethread=new Thread (new Runnable () { @Override public void Run () { synchronized (vector) {for (int i=0;i
synchronized(vector) {for (int i= 0;i
If you remove the red, the Exception inthread"Thread-132" Java.lang.ArrayIndexOutOfBoundsExceptionwill appear. Although the get (), remove (), and size () methods of the vectors used here are synchronous, in a multithreaded environment, it is still unsafe to use this code if you do not do extra synchronization on the method call side. Because if another thread happens to delete an element in the wrong time, and the sequence number I is no longer available, then using I to access the array will throw a arrayindexoutofboundsexception. If we want to make sure that this code can be executed correctly , we have to change the definition of Removethread and printthread to a red part.
Relative Thread safety
The relative thread safety is the thread safety we usually talk about, it needs to ensure that the individual operation of this object is thread-safe, we do not need to do extra safeguards when calling, but for some sequential calls in a particular order, it may be necessary to use an additional synchronization method at the caller to ensure the correctness of the call. In the Java language, most thread-safe classes fall into this type, such as the collection of vectors, HashTable, collections, Synchronizedcollection () method wrappers, and so on.
Thread compatible
Thread compatibility refers to the fact that the object itself is not thread-safe, but it is possible to ensure that the object is safe to use in a concurrent environment by using synchronous means correctly on the caller, and we usually say that a class is not thread-safe, and most of the time it refers to this situation. Most of the classes in the Java API are thread-compatible, such as the collection classes ArrayList and HashMap, which correspond to the previous vectors and Hashtable.
Thread antagonism
Thread antagonism is code that cannot be used concurrently in a multithreaded environment, regardless of whether the caller has taken synchronization measures. Because the Java language is inherently multi-threaded, threading against this multi-threaded code is rarely seen, and is often harmful, should be avoided as much as possible. A thread-antagonistic example is the suspend () and resume () methods of the thread class, and if there are two threads holding a thread object at the same time, one tries to go to the thread, and the other tries to recover the threads, and if the concurrency occurs, regardless of whether the call is synchronized, The target thread is at risk of deadlock, and if the thread that suspend () breaks is the one that is about to execute resume (), then a deadlock must be created. It is for this reason that the suspend () and resume () methods have been deprecated (@Deprecated) by the JDK declaration. Common thread-antagonistic operations include System.setin (), Sytem.setout (), and System.runfinalizersonexit ().
Thread-Safe Implementation method Mutex synchronization
Mutual Exclusion Synchronization (Mutual exclusion&synchronization) is a common method of concurrency correctness assurance. Synchronization is when multiple threads concurrently access shared data, ensuring that shared data is used by only one (or some, use of semaphores) threads at the same time. While mutual exclusion is a means of realizing synchronization, the critical section (Critical), mutex (mutex) and semaphore (Semaphore) are the main mutually exclusive implementations . Therefore, in these 4 words, mutual exclusion is the cause, synchronization is the fruit; mutual exclusion is the method, synchronization is the purpose.
In Java, the most basic mutually exclusive synchronization means is the Synchronized keyword, synchronized keyword after compiling, will be in the synchronization block before and after the formation of Monitorenter and monitorexit the two bytecode instructions, These two bytecode require a parameter of type reference to indicate the object to lock and unlock. If the synchronized in a Java program explicitly specifies an object parameter, that is the object's reference, and if it is not explicitly specified, then the instance method or class method is modified according to synchronized. To take the corresponding object instance or class object as the lock object.
According to the requirements of the virtual machine specification, when executing the monitorenter instruction, the first attempt is to obtain the lock of the object. If the object is not locked, or when the front-thread already has the lock of that object, the lock counter is added 1, corresponding, the lock counter will be reduced by 1 when the monitorexit instruction is executed, and the lock will be released when the counter is 0 o'clock. If an object lock fails, the current thread will block the wait until the object lock is freed by another thread.
There are two points that require special attention in the description of the behavior of Monitorenter and Monitorexit in the virtual machine specification. First, the synchronized synchronization block is reentrant to the same thread, without the problem of locking itself up. Second, the synchronization block blocks the entry of the other threads after the entered thread has finished executing. Java threads are mapped to the native threads of the operating system, and if you want to block or wake up a thread, you need the operating system to do it, which requires a transition from a user state to a kernel mindset, so the state transition takes a lot of processor time. For code-simple synchronization blocks (such as getter () or setter () methods that are synchronized decorated), state transitions can consume longer than the user code executes. So synchronized is a heavyweight (heavyweight) operation in the Java language, and experienced programmers will use it when it is really necessary. The virtual machine itself will also perform some optimizations, such as adding a spin-wait process before notifying the operating system to block threads, avoiding frequent entry into the nuclear mindset.
In addition to synchronized, We can also use the Java.util.concurrent (J.U.C) package in the re-entry lock (Reentrantlock) to achieve synchronization, in the basic usage, reentrantlock and synchronized very similar, they all have the same thread reentrant feature, just code write There is a difference in law, one that shows the API level of mutexes (the Lock () and the Unlock () method with the try/finally statement block) and the other as the native syntactic level mutex.
However, there are 3 more advanced features compared to Synchronized,reentrantlock: Waiting is interruptible, a fair lock can be achieved, and a lock may bind multiple conditions.
- Waiting for interruptible means that when the thread holding the lock does not release the lock for a long time, the waiting thread can choose to discard the wait and handle other things instead, and the interruptible feature is useful for processing a synchronization block that takes a very long time to execute.
- A fair lock is when multiple threads are waiting for the same lock, and the lock must be obtained sequentially in the order in which the lock is requested, whereas an unfair lock does not guarantee that any thread that waits for a lock is given a chance to acquire a lock when the lock is released. The lock in synchronized is not fair, Reentrantlock is also unfair by default, but a fair lock can be required through constructors with Boolean values.
- Lock binding multiple conditions means that a Reentrantlock object can bind multiple condition objects at the same time, whereas in synchronized, the Wait () and notify () or Notifyall () methods of the lock object can implement an implied condition, If you want to associate with more than one condition, you have to add a lock extra, and Reentrantlock does not need to do so, just call the Newcondition () method multiple times.
If you need to use the above features, choosing Reentrantlock is a good choice.
Non-blocking synchronization
The main problem with mutex synchronization is the performance issues caused by thread blocking and wake-up, so this synchronization is also known as blocking synchronization (Blocking synchronization). In the way of dealing with the problem, the mutex synchronization is a pessimistic concurrency policy , always think that as long as not to do the correct synchronization measures (such as locking), then there will be a problem, regardless of whether the sharing of data is really competition, it will be locked (this is discussed in the conceptual model, In fact, the virtual opportunity optimizes a large part of the unnecessary locking), the user-state kernel mentality conversion, the maintenance lock counter and checks if there is a blocked thread that needs to wake up and so on. With the development of the hardware instruction set, we have another option: optimistic concurrency Strategy based on conflict detection, in layman's words, first, if no other thread is competing for shared data, then the operation succeeds; if there is contention for the shared data, a conflict occurs. Then take other compensation measures (the most common compensation measure is to continually retry until successful), many implementations of this optimistic concurrency policy do not need to suspend the thread, so this synchronization operation is called non-blocking synchronization (non-blocking synchronization) .
Why is it that the use of optimistic concurrency strategies requires "development of hardware instruction sets"? Because we need to operate and conflict detection These two steps have atomicity, what is the guarantee? If we use mutually exclusive synchronization to guarantee the loss of meaning, so we can only rely on hardware to do this thing, hardware to ensure that a semantically seemingly need to operate a number of actions only through a single processor instruction can be completed, such directives commonly used are:
Test and set (Test-and-set).
Get and Add (fetch-and-increment).
Swap (Swap).
Compare and Exchange (Compare-and-swap, hereinafter referred to as CAs).
Load link/Condition Store (load-linked/store-conditional, hereinafter referred to as LL/SC).
Of these, the previous 3 are the processor instructions that existed in most instruction sets in 20th century, and the latter two are new to modern processors, and the purpose and function of these two directives are similar. In the IA64, x86 instruction set has the CMPXCHG instruction to complete the CAS function, in the SPARC-TSO also has the Casa instruction implementation, but in the arm and the PowerPC architecture, then needs to use a pair of Ldrex/strex instruction to complete the LL/SC function. The CAS directive requires 3 operands, namely the memory location (which can be easily understood in Java as the memory address of the variable, denoted by V), the old expected value (denoted by a), and the new value (denoted by B). When the CAS instruction executes, the processor updates the value of V with the new value B if and only if v conforms to the old expected value of a, otherwise it does not perform the update, but regardless of whether the value of V is updated, the old value of V is returned, and the process described above is an atomic operation. After JDK 1.5, CAS operations are only available in Java programs, This operation is provided by a few methods such as Compareandswapint () and Compareandswaplong () inside the Sun.misc.Unsafe class, and the virtual machine has a special handling of these methods internally, and the result of the immediate compilation is a platform-related processor CAS directive, and no party The process of invoking the method, or can be considered unconditional inline, this method of special processing by the virtual machine is called intrinsic function (intrinsics), similar intrinsic function also has math.sin () and so on.
Because the Unsafe class is not provided to the user program call Class (Unsafe.getunsafe () code restricts only the class loader (Bootstrap ClassLoader) loaded by class to access it), so, if you do not use reflection means, We can only use it indirectly through other Java APIs, such as the integer Atom class inside the J.U.C package, where the Compareandset () and Getandincrement () methods all use the unsafe class's CAS operations.
The Incrementandget () method continuously attempts to assign a new value of 1 greater than the current value to itself in an infinite loop. If it fails, it means that the value has been modified in the "get-set" operation, so the next operation is cycled again until the setting is successful. Although CAs looks beautiful, it is clear that this operation cannot cover all the usage scenarios for mutually exclusive synchronizations, and CAS is semantically imperfect, and there is a logical flaw: if a variable v is first read a value, and when it is ready to be assigned, it is still a value. So can we say that its value has not been changed by another thread? If during this period its value has been changed to B and later changed back to a, the CAS operation will be mistaken for it has never been changed. This vulnerability is called the "ABA" issue of CAS operations. J.U.C package in order to solve this problem, a tagged atomic reference class "Atomicstampedreference" is provided, which can guarantee the correctness of the CAs by controlling the version of the variable values. But for now, this kind of "chicken", most of the time, the ABA problem will not affect the correctness of program concurrency, if you need to solve the ABA problem, instead of the traditional mutex synchronization may be more efficient than the atomic class.
No synchronization scenario
To ensure thread safety, it is not necessarily necessary to synchronize, the two have no causal relationship. Synchronization is only a means of ensuring the correctness of shared data contention, and if a method does not involve sharing data, it naturally does not require any synchronization to ensure correctness, so some code is inherently thread-safe.
Reentrant code: This code, also known as pure Code, can break it at any moment of execution of the code, instead of executing another piece of code (including recursively invoking itself), and the original program will not have any errors after control returns. reentrant In contrast to thread safety, reentrant is a more basic feature that guarantees thread safety , that is, all reentrant code is thread-safe, but not all thread-safe code is reentrant. Reentrant code has some common characteristics, such as not relying on the data stored on the heap and the common system resources, the amount of state used by the parameters passed in, not calling non-reentrant methods, and so on. We can use a simple principle to determine whether the code is reentrant: If a method, its return result is predictable, as long as the same data input, you can return the same results, it satisfies the requirements of reentrant, of course, is thread-safe.
Thread native Storage (thread local Storage): If the data needed in a piece of code must be shared with other code, then see if the code for the shared data is guaranteed to execute on the same thread? If guaranteed, we can limit the visible scope of shared data to the same thread, so that there is no need for synchronization to ensure that there is no data contention between threads. Applications that meet this feature are not uncommon, and most of the architectural patterns that use the consumer queue, such as the "producer-consumer" model, consume the product as much as possible in one thread, and one of the most important application examples is the "one request for one server thread" in the classic web interaction model. (thread-per-request) processing, the wide application of this approach makes it possible for many Web server applications to use thread-local storage to address thread-safety issues.
In the Java language, if a variable is to be accessed by multithreading, it can be declared as "volatile" using the volatile keyword; If a variable is to be exclusive to a thread, there is no __declspec in Java like C + + (thread). In Visual C + + is the "__declspec" keyword, and in gcc it is "__thread". Such a keyword, however, can still be implemented through the Java.lang.ThreadLocal class to implement the functionality of thread-local storage . Each thread has a Threadlocalmap object in its thread object that stores a set of k-v value pairs with threadlocal.threadlocal hashcode as the key, and local thread variables as values. The Threadlocal object is the access entry for the current thread's threadlocalmap, and each Threadlocal object contains a unique Threadlocalhashcode value. Using this value, the corresponding local thread variable can be retrieved in the thread k-v value pair.
Thread Safety in Java