5. How to implement thread safety

Source: Internet
Author: User
Tags cas instance method mutex semaphore

Now that you know what thread safety is, then you're going to implement thread safety. It is also important to understand the synchronization mechanisms and locking mechanisms provided by virtual machines. 1. Mutual exclusion SynchronizationMutex synchronization is when multiple threads concurrently access shared data, ensuring that shared data is used by only one thread at a time. In this place, mutual exclusion is the result, synchronization is the fruit; the implementation of synchronization is achieved through mutual exclusion; Common mutex implementations are: critical section (Critical selection), mutex (mutex), and semaphore (semaphore) In Java, the most basic means of mutual exclusion is the Synchronized keyword, synchronized after compiling, the synchronization block will be formed before and after the Monitorenter and monitorexit two byte-code command, These two bytecode require a parameter of type reference to indicate which objects need to be locked and unlocked.  If synchronized explicitly points to the object parameter, that is the reference to this object, if not, then according to the modification is the instance method or class method, to obtain the corresponding object instance, or a class object as the lock object. Synchronized is reentrant on the same thread and does not appear to lock himself up. The synchronization block will block the entry of other threads until the execution ends. Since the Java thread is to be mapped to the native thread of the operating system,If you block or wake up a thread, you need the operating system to help complete, which needs to be converted from the user state to the core State, this conversion consumes a lot of CPU time, for the code simple synchronization block, it may be more than the time to execute。 Therefore, synchronized is a heavyweight operation and is generally used only when it is really necessary. Of course, the virtual machine also has some optimizations for this, such as blocking the thread before the advanced paragraph spin wait. We can also achieve synchronization by Java.util.concurrent under the Reentrantlock. Compared to Synchronized,reentrantlock offers some more flexible and advanced features, mainly: wait can be interrupted:When the thread holding the lock does not release the lock for a long time, the waiting thread can choose to give up waiting; Fair Lock:When multiple threads acquire a lock, the lock must be acquired in sequence according to the time the lock is requested; (strictly queued to prevent some threads from getting locks) To bind multiple conditions:A Reentrantlock object can bind more than one condition object, whereas in synchronized, the Wait () and notify () of the lock object can implement an implied condition that, if associated with an extra condition, has to be locked  Reentrantlock only needs multiple new Condition (). Performance, 1.5 when the reentrantlock slightly better, jdk1.6 after the two basic flat, and the virtual machine in favor of the synchronized optimization, so performance is no longer the two considerations, can be achieved in the case of priority synchronized. 2, non-blocking synchronizationThe main problem with mutex synchronization is the performance problems caused by thread blocking and wake-up, so this implementation is also called blocking synchronization. The mutex synchronization belongs to a pessimistic concurrency policy in the way of dealing with the problem. With the development of the hardware instruction set, we have another choice: optimistic concurrency strategy based on conflict detection. That is, the operation succeeds if no other thread uses the shared data, and if so, then the compensation is taken.  This method does not need to suspend the thread, so called: non-blocking synchronization (non-blocking synchronization). The so-called "hardware instruction Set" refers to the new CAS directive (Compare-and-swap, compare and Exchange) in modern instruction set.  jdk1.5 after the CAS related operations, such as the Sun.misc.Unsafe class inside the Compareandswapint () method, the virtual machine internal to these methods have been processed, the result is a platform-related processor CAS instructions. Although CAs looks beautiful, it does not cover all the usage scenarios for mutually exclusive synchronizations, and CAS is semantically imperfect because there is a logical vulnerability: if the variable v is a value for the first time, and if it is a value when it is ready to be assigned, So we can tell if V has not been modified by another thread? Obviously can not, if during this time thread to change V to B, and re-modify in order to A,cas will think that has not been modified, the vulnerability is called CAS "ABA problem." The concurrent package provides a atomicstampedreference to solve this problem, the principle is to set the version number to ensure correctness (database optimistic lock, is not very similar), but for the moment this class is a little "chicken", Most ABA problems do not affect concurrency correctness, and if you need to solve ABA problems, using mutex synchronization may be more efficient than atomic classes. 3. No synchronization schemeTo ensure thread safety, it is not always important to synchronize. There is no causal relationship between the two. Synchronization is only a means of guaranteeing the correctness of shared data contention. Some of the code is inherently thread-safe, such as: can re-enter code: This code is also called Pure code. You can break it at any point in the execution of the code and execute another piece of code, and the original program will not have any errors after control returns. Reentrant code has some common characteristics, such as: Do not rely on the data stored on the heap and the common system resources, the amount of state used by parameters passed in, do not call non-reentrant methods and so on. Thread Local Storage: If the data required in a piece of code is fully contained in the same thread, if this is guaranteed, it will not cause data inconsistency due to competing with other threads, there is no thread risk, it is thread safe. We usually do not consider multithreading in web development, because the "one request corresponds to one server thread" method in the Web interaction model.

5. How to implement thread safety

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.