Java thread safety and lock optimization

Source: Internet
Author: User
Tags cas instance method mutex

object-oriented programming idea is to stand in the real world to abstract and solve the problem, he regards the data and behavior as part of the object, so that the programmer can be in line with the real world thinking way to write and organize programs. a proper definition of thread safety: When multiple threads access an object, it is thread-safe to invoke the behavior of the object if it is not necessary to consider the scheduling and alternation of these threads in the running environment, the need for additional synchronization, or any other coordinated operation by the caller, which can obtain the correct result. Sort by a strong-to-weak level of security in terms of thread safety, you can divide the data that is shared by various operations in the Java language into the following 5 classes : Immutable, Absolute thread-saferelative thread safety, thread compatibility, and thread antagonism. (1) Immutable: Immutable objects must be thread-safe, regardless of the method implementation of the object or the caller of the method, there is no need to take any more thread-safe safeguards,in the Java language, if the shared data is a basic data type, it can be guaranteed to be immutable as long as it is redefined with the final keyword, and if the shared data is an object, you need to ensure that the object's behavior does not affect its state any more. Just like the object of the Java.lang.string class, she is a typical immutable object, we call his substring (), replace () and other methods will not affect his original value, will only return a newly constructed string object. (2) Absolute thread Safety: a class to achieve "no matter what the runtime environment, the caller does not need any additional synchronization measures" often need to pay a great, even sometimes unrealistic price, in the Java API labeled itself is a thread-safe class, most are not absolute thread safety, For example, Java.util.vector is a thread-safe container, because its add (), get (), size () and other methods are synchronized decorated, although this is very inefficient, but it is safe, but in a multi-threaded environment, If you do not do extra synchronization on the method call, it is still unsafe to use this code, 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 an exception, if you want to ensure that the code is properly executed, You have to change the code. (3) Relative thread safety: relative thread safety is what we call thread safety, it needs to ensure that the individual operation of this object is thread-safe, there is no need to do extra safeguards when calling, but for some sequential calls in a particular order, It may be necessary to use additional synchronization at the caller's side to ensure the correctness of the call, and most thread-safe classes fall into this type. (4) Thread compatibility: Thread compatibility means that the object itself is not thread-safe, but can be used to ensure that the object is safe to use in the concurrency environment by using the correct synchronization method at the caller's side .(5) Thread antagonism: Thread antagonism refers to code that cannot be used concurrently in a multithreaded environment, regardless of whether the caller has taken synchronization measures, such as the Suspend () and resume () methods of the thread class, if two threads hold a thread object at the same time, and an attempt is made to go to the interrupt thread, Another attempt to resume the thread, concurrently, is the risk of a deadlock, regardless of whether the call is synchronized or not. So these two methods are deprecated by the JDK declaration,thread-Safe implementation methods:(1) Mutex synchronization (blocking synchronization): Synchronization means that when multiple threads concurrently access shared data, it is ensured that the shared data is used only by one thread at a time, and that mutual exclusion is a means of realizing synchronization.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 reference type parameter to indicate the object to lock and unlock, if the Java program synchronized explicitly specify the object parameters, that is the object reference, if not explicitly specified, That is, depending on whether the synchronized modifies the instance method or the class method, to fetch the corresponding object instance or the classes object as the lock object, because the synchronization block blocks the entry of the other threads after the thread has been executed, and the Java thread is mapped to the native thread of the operating system. If you want to block or wake up a thread, you need the operating system to help complete, this needs to switch from the user state to the kernel mentality, the state transition takes a lot of processor time, so synchronized is a heavy-weight operation of the Java language. There is also the way to achieve synchronization is java.util.concurrent in the package of the re-entry lock (Reentrantlock) to achieve synchronization, their usage is basically similar, all have reentrant, the difference is the API level of the mutex, the other is the native syntactic level of the mutex, compared to Sychroniz Ed,reetrantlock added some advanced features (wait for interruptible, can achieve fair lock, lock can bind multiple conditions) p392 page(2) non-blocking synchronization: With the development of the hardware instruction set, we have another option: the optimistic concurrency policy based on conflict detection, that is, the operation is first, if no other thread contention shared data, then it succeeds, if there is contention for shared data, then take other compensation measures, Many implementations of this strategy do not need to suspend the thread, so it is called non-blocking synchronization,(3) No synchronization scheme: To ensure thread safety, and not necessarily to synchronize, synchronization is only to ensure the correctness of data sharing contention, if a method itself does not involve data sharing, there is no need to synchronize measures to ensure correctness, two types of code is inherently safe, can re-enter code and thread local storage. Lock Optimization measures:(1) Spin lock and adaptive spin: Since the most significant performance impact of mutex synchronization is the implementation of blocking, both the suspend thread and the recovery thread need to be transferred to the kernel state, so if there is more than one processor on the physical machine, allowing two or more threads to execute concurrently in parallel, We can let the thread that asks for the lock "Wait a moment", but not abandon the processor's execution time, see if the thread holding the lock will release the lock soon, in order for the thread to wait, we just have to let the thread perform a busy loop (spin), which is called a spin lock. jdk1.4.2 has been introduced, but the default is closed, in the jdk1.6 is turned on by default, the spin wait itself to avoid the cost of thread switching, but it takes processor time, if the lock is occupied for a short time, the spin-wait effect is very good, if it takes too long, it will result in a waste of performance, so since The time to wait must have a certain limit, if more than a limited number of times have not succeeded in obtaining a lock, the traditional way to suspend the thread,jdk1.6 introduces an adaptive spin lock, which means that the spin time is not fixed and is determined by the previous spin time in the same lock and the state of the lock holder. (2) Lock Elimination (P398): Lock elimination refers to the virtual machine instant compiler at run time, to some code on the requirements of synchronization, but it is detected that there is no possibility of sharing data competition to eliminate the lock, lock elimination is based on data from the escape analysis support,(3) lock coarsening: In most cases, it is always recommended to limit the scope of the synchronization block as small as possible, only in the actual scope of the shared data Zhongcai synchronization, so that the number of operations that need to be synchronized as small as possible, but if the operation of some columns on the same object repeatedly lock and unlock, will result in unnecessary performance losses, such as:Public string concatstring (String s1,string s2,string S3) {stringbuffer sb = new StringBuffer ();sb.append (S1);sb.append (S2);Sb.sppend (S3);return sb.tostring ();}Three append operations require the same object to be locked, so the range of lock synchronization is extended (coarsening) to the outside of the entire sequence of operations. (4) Lightweight Lock: First understand the object head of the hotspot virtual machine is divided into two parts, the first part is used to store the object's own run-time data, such as hash code, generational age, etc., officially known as "Mark Word", the other part is used to store pointer to the method area object type dataLock Process: When the code enters the synchronization block, if the object is not locked, the virtual machine will first establish a space named lock record in the stack frame of the current thread to store the lock object's current copy of Mark Word. The virtual machine then uses the CAS action to attempt to update the object's mark Word to a pointer to the lock record, and if the update action succeeds, the thread has a lock on the object, and the object Mark Word's lock flag bit is converted to "00", which means that the object is in a lightweight lock state. If the update operation fails, the virtual machine first checks to see if the object's mark word points to the stack frame of the current thread, and if only the current thread has a lock on the object, it can go directly to the synchronization block to continue execution, otherwise the lock object has been preempted by another thread. If more than two threads are contending for the same lock, the lightweight lock expands to a heavyweight,(5) biased Lock: The purpose is to eliminate the data in the non-competitive situation of the synchronization of the original language, further improve the performance of the program,A bias lock means that the lock will be biased towards the first thread that gets him, and if the lock is not fetched by another thread during the next execution, the thread that holds the biased lock never needs to be synchronized.procedure: Assuming that the current virtual machine has a biased lock enabled, when the lock object is fetched by the thread for the first time, the virtual machine will set the flag bit in the object header to "01", that is, biased mode, and the ID of the thread to which the lock was obtained by using the CAS operation is recorded in the exclusive Mark Word. If the CAs operation succeeds, the virtual machine can no longer perform any synchronization when the thread that is holding the lock is entered into the lock-related synchronization block each time, and when another thread attempts to acquire the lock, the bias mode is ended,biased locking can improve performance with synchronous but non-competitive programs, but if the majority of the program's locks are always accessed by different threads, the bias pattern is redundant,

Java thread safety and lock optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.