Lock expansion

If a series of continuous operations repeatedly lock and unlock the same object, or even the lock operation occurs in the loop body, frequent mutually exclusive synchronization operations will lead to unnecessary performance loss even if there is no thread competition. If the virtual machine detects that such a series of piecemeal operations lock the same object, it will expand (expand) the scope of lock synchronization to the outside of the whole operation sequence (only lock once by multiple lock programming).

An extreme case requiring lock coarsening is:

The above code requests, synchronizes and releases locks every time it loops. It seems that there is no problem, and the JDK will optimize the requests for such code locks. However, it is better to write the locking code outside the loop body so that the lock request can meet our requirements. Unless there is a special need: the loop takes a long time, But other threads can't afford to wait. Give them a chance to execute.

The code after lock coarsening is as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>