当前位置:网站首页>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
dream4s
Contact 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
边栏推荐
- Chinese scientists reveal a new mechanism for breaking through the bottleneck of rice yield
- 不断下沉的咖啡业,是虚假的繁荣还是破局的前夜?
- PTA: Romantic reflection [binary tree reconstruction] [depth first traversal]
- Is CICC fortune a company with CICC? Is it safe
- Go language ⌈ mutex and state coordination ⌋
- Quel est le fichier makefile?
- Develop a chrome plug-in from 0 (2)
- What are the common proxy IP problems?
- 【2019-CVPR-3D人体姿态估计】Fast and Robust Multi-Person 3D Pose Estimation from Multiple Views
- What business scenarios will the BGP server be used in?
猜你喜欢
Latin goat (20204-2022) - daily question 1
想体验HomeKit智能家居?不如来看看这款智能生态
Common formatting problems after word writing
002_Redis_String类型常见的操作命令
009_Redis_RedisTemplate入门
002_ Redis_ Common operation commands of string type
012_ Access denied for user ‘root‘@‘localhost‘ (using password: YES)
C语言中*与&的用法与区别 以及关键字static和volatile 的含义
世界读书日 | 技术人不要错过的好书(IT前沿技术)
Introduction to esp32 Bluetooth controller API
随机推荐
002_ Redis_ Common operation commands of string type
What should I pay attention to when using proxy IP?
从开源爱好者到 Apache 董事,一共分几步?
89 régression logistique prédiction de la réponse de l'utilisateur à l'image de l'utilisateur
每日一题冲刺大厂第十六天 NOIP普及组 三国游戏
Micro build low code zero foundation introductory course
Is CICC fortune a company with CICC? Is it safe
001_redis设置存活时间
What businesses use physical servers?
What is BGP server and what are its advantages?
Analyze the advantages and disadvantages of tunnel proxy IP.
配置iptables实现本地端口转发的方法详解
Unicorn bio raised $3.2 million to turn prototype equipment used to grow meat into commercial products
006_ redis_ Jedis quick start
不断下沉的咖啡业,是虚假的繁荣还是破局的前夜?
Talk about biology live broadcast: Dr. Wang Ziyuan, a lake view biology, exploring hepatitis B with gene therapy
How to set computer IP?
Unity editor hierarchy drop-down menu extension
Tp6 Alibaba cloud SMS window reports curl error 60: SSL certificate problem: unable to get local issuer certificate
006_redis_jedis快速入门