当前位置:网站首页>Synchronized lock and its expansion
Synchronized lock and its expansion
2022-04-23 02:14:00 【Java knowledge map】
One 、 preface
In concurrent programming ,synchronized The lock is simple to use , Inter process synchronization is widely used . The principle and lock upgrade process are explored below .
Two 、 How to use
1、 Decorated instance method
When the instance method is synchronized When decorating , All threads calling this method through the current instance share a lock , When different objects call this method, the threads do not affect each other .
public class A { public synchronized void func() { }}
When using synchronized Lock modifier instance method , The lock is added to the instance of the current class , How many instances and how many locks can be added .
2、 Decorated code block
Decorated code blocks are less granular than decorated methods . When the instance method code block is synchronized When decorating , All threads calling this method through the current instance share a lock , When different objects call this method, the threads do not affect each other .
public class B { public void func() { synchronized (this) { } }}
When using synchronized Lock modifier code block , The lock is added to the instance of the current class , How many instances and how many locks can be added .
3、 Modified static method
When static methods are synchronized When decorating , Whole JVM All threads calling this method are bound by the same lock .
public class C { public static synchronized void func() { }}
When using synchronized Lock decorated static methods , The lock is added to the of the current class Class object On , Add at most one lock .
Don't use it unnecessarily synchronized Modified static method
3、 ... and 、 Lock upgrade
Java 8 What is used synchronized The lock is optimized , There is Biased locking 、 Lightweight lock 、 Heavyweight lock Equal state .
( One ) Biased locking
There is no lock competition between threads , At most one thread has the need to acquire a lock , Common scenarios are Single threaded program .
1、 Recognition method
The identification to judge whether the lock is biased is to check whether there is and only one thread calling this method .
In multithreaded programming , The lock decorated method is only called by a single thread and almost does not exist , Therefore, the bias lock is more chicken ribs : If you can make it clear that a single thread calls the target method , Using lockless programming is more appropriate .
2、 Performance comparison
The performance difference between no lock and bias lock is very close , Almost negligible .
( Two ) Lightweight lock
There are locks between threads Pseudo competitive behavior , That is, there will never be two threads applying for locks at the same time , Although each thread has the need to use locks , But it's alternating locks .
1、 Recognition method
When two or more threads call a lock decorated method , Then at least it's a lightweight lock .
2、 Performance comparison
Lightweight lock because there are no two threads competing with each other at the same time , So there are no threads Blocking - Wake up the Context switch of , Therefore, the performance is much higher than that of heavyweight lock .
( 3、 ... and ) Heavyweight lock
There are locks between threads Substantial competition Behavior , There is a need to obtain locks between threads , But time cannot be staggered , Blocking wait of mutex .
1、 Recognition method
When it is certain that at least two or more threads call the lock decorated method , Thread calls are random , Then the probability is heavyweight lock .
2、 Performance comparison
Heavyweight locks involve thread blocking - Wake up context switching , Cause comparison with unlocked state , It's a lot less efficient .
Four 、 Other contents
( One ) Nature of lock
1、 Fairness
synchronized The lock is Not fair lock , No, FIFO The queue mechanism ensures that threads competing for locks have a chance to obtain locks .
2、 Reentrant
synchronized The lock is Reentrant lock , Reentrant means that nested calls do not cause deadlock problems .
3、 Happy ( sad ) Watch the lock
synchronized Lock is a pessimistic lock , Achieve synchronization between threads by locking .
( Two ) Understand heavyweight locks
In multithreaded environment , If you use synchronized lock , Then the probability will be upgraded to heavyweight lock . Biased locks and lightweight locks are not intentional , It's hard to exist , More importantly, comparison helps understand the performance of heavyweight locks .
Although heavyweight locks will have a great impact on performance , However, it is still an effective means to solve the synchronization between threads .
1、 Suggestions for choosing locks
When the execution time of the method or code block decorated by the lock is relatively long Long when , Select thread based blocking - The method of wake-up and context switching for thread synchronization is relatively efficient .
When the execution time of the method or code block decorated by the lock is relatively long short when , Other alternative locks shall be selected , Such as spin lock .
( 3、 ... and ) understand synchronized lock
In the actual multi-threaded scenario development ,synchronized There is a high probability that the lock will be upgraded to the heavyweight lock , Because of its one-way upgrade , Heavyweight state synchronized Locks may adversely affect the concurrency of actual business , Manual selection of other locks may be more appropriate .
synchronized Locks can only be used to solve synchronization between different threads in the same process , For distributed projects, thread synchronization across cities depends on distributed locks ,synchronized The more meaning of lock is to understand the process of lock .
Like this article, point to ️ Fabulous ️ support , If necessary , Via wechat
dream4sContact with me . The relevant source code is GitHub, The video explanation is in B standing , This article is collected in Blog world .
版权声明
本文为[Java knowledge map]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230213101431.html
边栏推荐
猜你喜欢

How to choose a good dial-up server?

009_ Redis_ Getting started with redistemplate

Wechat public platform test number application, authorized login function and single sign on using hbuilder X and wechat developer tools

What is a dial-up server and what is its use?

005_ redis_ Set set

Talk about biology live broadcast: Dr. Wang Ziyuan, a lake view biology, exploring hepatitis B with gene therapy

They are all intelligent in the whole house. What's the difference between aqara and homekit?

Common formatting problems after word writing
![leetcode:27. Remove element [count remove]](/img/af/e5cd9ef8dc43aab4ddf016600ffc4a.png)
leetcode:27. Remove element [count remove]
Unicorn bio raised $3.2 million to turn prototype equipment used to grow meat into commercial products
随机推荐
中金财富跟中金公司是一家公司吗,安全吗
005_redis_set集合
Halo open source project learning (I): project launch
006_redis_SortedSet类型
The importance of ERP integration to the improvement of the company's system
小程序 读取文件
Dynamic batch processing and static batch processing of unity
从0开始开发一个chrome插件(2)
Numerical remapping method (remap)
2018 China Collegiate Programming Contest - Guilin Site J. stone game
002_ Redis_ Common operation commands of string type
C standard library - < time h>
Analyze the three functions of static proxy IP.
Heap overflow of kernel PWN basic tutorial
Multithreading technology core
Introduction to micro build low code zero Foundation (lesson 2)
89 régression logistique prédiction de la réponse de l'utilisateur à l'image de l'utilisateur
想体验HomeKit智能家居?不如来看看这款智能生态
012_ Access denied for user ‘root‘@‘localhost‘ (using password: YES)
VMware virtual machine installation openwrt as side route single arm route img image to vmdk