In layman's Java Concurrency (15): Lock mechanism Part 10 lock some other problems [turn]

Source: Internet
Author: User

Mainly talk about the performance of the lock and some other theoretical knowledge, the main source of the content is "Java Concurrency in Practice", combined with their own understanding and practical application of the lock mechanism to a small summary.

One of the first things to emphasize is that all locks (including built-in locks and advanced locks) are performance-intensive, that is, in high concurrency, due to the lock mechanism caused by the context of switching, resource synchronization and other consumption is very considerable. In some extreme cases, threads may consume more of the lock than the thread itself consumes. Therefore, if possible, in any case, as little as possible to use the lock, if the inevitable use of non-blocking algorithm is a good solution, but it is not absolute.

Internal lock

The Java language guarantees atomicity by synchronized keywords. This is because each object has an implied lock, which is also known as a monitor object. This internal lock is automatically acquired before entering the synchronized, and the lock is automatically released once you leave this method, regardless of the way it is passed in and out. Obviously this is an exclusive lock, and each lock request is mutually exclusive. Compared to the many advanced locks described earlier (lock/readwritelock, etc.), the synchronized cost is higher than the latter. But the grammar of synchronized is relatively simple, and it is easier to use and understand, it is not easy to make mistakes on the wording. And we know that lock is likely to be deadlocked once the lock () method has been called to get the locks and is not released correctly. So lock's release is always followed by the finally code block, which is also an adjustment and redundancy in the code structure. In addition to the previous introduction said lock implementation has used the hardware resources to the extreme, so the future can be optimized for less space, unless the hardware has a higher performance. But synchronized is only a specification of the implementation of the different platforms in different hardware has a high space for improvement, the future of Java in the lock optimization will be mainly on this.

Performance

Because locks always have a performance impact, it becomes particularly important to use locks and locks. If a forced exclusive lock is used in a high-concurrency Web request, you can see that the throughput of the web will drop sharply.

To take advantage of concurrency to improve performance, the starting point is to make more efficient use of existing resources while allowing the program to exploit as many resources as possible. This means that the machine is as busy as possible, usually meaning that the CPU is busy computing, not waiting. Of course the CPU has to do something useful, not a meaningless loop. In practice, of course, some resources are usually reserved for emergency situations, which can be seen in a number of instances later in the thread pool concurrency.

Thread blocking

The implementation of the lock mechanism usually requires the support of the operating system, which obviously increases overhead. When a lock competes, the failed thread is bound to block. The JVM can either spin-wait (keep trying, know how successful, many CAs do), and can suspend blocked threads in the operating system until it expires or is woken up. Typically, this depends on the cost of the context switch and the relationship between the time it takes to get the lock to wait. Spin waits are suitable for relatively short waits, while suspended threads are better suited for more time-consuming waits.

A thread may be suspended because it cannot acquire a lock, or it requires a specific condition, or a time-consuming I/O operation. Suspending a thread requires two additional context switches, as well as multi-resource mates such as the operating system, cache, and so on: if the thread is swapped out early, then once the lock or condition is met, then the thread needs to be swapped back to the execution queue, which can be time-consuming for a thread for a two-time context switch.

Lock competition

There are two conditions that affect the locking competition: the frequency at which the lock is requested and the time that the lock is held each time. Obviously when both are very small, lock competition will not become the main bottleneck. However, if the lock is not used properly, resulting in both are relatively large, then it is likely that the CPU can not effectively handle the task, the task is piled up heavily.

So there are three ways to reduce lock competition:

    1. Reduce the time of lock holding
    2. Reduce the frequency of lock requests
    3. Replace exclusive locks with shared locks

Dead lock

A thread can cause a deadlock if it never frees the resources it needs for another thread. There are two cases where a thread a never releases a lock, and B has no lock, so thread B is "dead", and in the second case, thread A has the lock y required by thread B, and thread B has the lock x required by thread A, then the thread A/b relies on each other to release the lock, and both "die" The

There is also a case where a deadlock occurs, and if a thread is always unable to be dispatched, the thread that waits for the result of this thread may be deadlocked. This situation is called thread starvation deadlock. For example, in the unfair lock described earlier, if some threads are very active, and in high concurrency, such threads may always get locks, then those threads with low activity may not be able to get locks, so that a "starvation" occurs.

The solution to avoid deadlocks is to request the lock as much as possible according to the use specification of the lock, in addition the request granularity of the lock is small (do not take the lock in place where the lock is not needed, the lock does not need to be released as soon as possible); the trylock or timing mechanism is always used in the advanced lock If the time has not yet acquired the lock then give up). Both of these methods in Gao Pei (lock) can effectively avoid deadlocks.

Live lock

A live lock describes a situation in which a thread always tries an operation and always fails. In this case, although the thread is not blocked, the character is always unable to be executed. For example, in a dead loop always try to do something, the result is always failed, and now the thread will never jump out of this loop. Another scenario is that each time a task is fetched from the queue header in a queue, each time it fails, and then the task is placed in the queue header, and then the task is removed from the queue header, and then the execution continues to fail.

There is also a kind of live lock mode occurs in the case of "Collision Association let": two people cross a log bridge, if the collision halfway, both sides politely quit and then try again. If you always fail, these two tasks will never be executed.

In short, the key to solve the lock problem is: From a simple start, first ensure the correct, and then start optimization.

In layman's Java Concurrency (15): Lock mechanism Part 10 lock some other problems [turn]

Related Article

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.