当前位置:网站首页>Synchronized keyword details
Synchronized keyword details
2022-07-29 01:15:00 【Kevin Zhang Junjie】
Preface
Thread safety is an important concern in concurrent programming , It should be noted that , There are two main causes of thread safety problems :
- One is the existence of shared data ( Also called critical resources )
- Second, there are multiple threads operating on shared data
So in order to solve this problem , We may need such a plan , When there are multiple threads operating on shared data , It is necessary to ensure that there is only one thread sharing data at the same time , Other threads must wait until the thread finishes processing the data , This approach has a noble name called mutex , That is to say, the lock that can achieve the purpose of exclusive access , That is to say, when a shared data is added with a mutually exclusive lock by the thread currently being accessed , At the same time , Other threads can only wait , Until the current thread finishes processing and releases the lock .
stay Java in , keyword synchronized Can guarantee at the same time , Only one thread can execute a method or a block of code ( It mainly refers to the operation of shared data in methods or code blocks ), At the same time, we should also pay attention to synchronized Another important role ,synchronized It can guarantee the change of a thread ( It's mainly about changes in shared data ) Seen by other threads ( Guaranteed visibility , Completely replaceable Volatile function ), This is really important .
Synchronized Use
A lock can only be acquired by one thread at a time , A thread that does not acquire a lock can only wait ;
Each instance should have its own lock (this), The different instances are independent of each other ; exception : The lock object is *.class as well as synchronized Modification is static Method time , All objects share the same lock
synchronized The method of decoration , Whether the method finishes executing normally or throws an exception , Both release locks
Object lock
Including method locks ( The default lock object is this, Current instance object ) And synchronization code block lock ( Specify the lock object by yourself )
Code block form : Manually specify locked objects , It's also this, It can also be a custom lock
Method lock form :synchronized Decorate common methods , The lock object defaults to this
Kind of lock
finger synchronize Modifies a static method or specifies that the lock object is Class object
synchronize Modified static method
synchronized Specifies that the lock object is Class object
In depth understanding of Synchronized
Use Synchronized What should we pay attention to
The lock object cannot be empty , Because the lock information is stored in the object header
Do not oversize , Affect the speed of program execution , Too much control , Writing code is also error prone
Avoid deadlock
If you can choose , Don't use Lock Don't use synchronized keyword , use java.util.concurrent All kinds of classes in the bag
synchronized Is it a fair lock
synchronized It's actually unfair , It is possible for the new thread to get the monitor immediately , The thread that has been waiting for a long time in the waiting area may wait again , This is good for improving performance , But it can also lead to hunger .
Synchronized The defects of
Low efficiency : Less lock release , The lock will not be released until the code is executed or abnormally terminated ;
You cannot set a timeout when trying to acquire a lock , You cannot interrupt a thread that is using a lock , Relatively speaking ,Lock You can interrupt and set timeout ;
inflexible : Lock and release at a single time , Each lock has only one single condition ( An object ), Relatively speaking , Read and write locks are more flexible
There is no way to know if the lock was successfully acquired , Relatively speaking ,Lock You can get the status
Lock Solve the corresponding problems
Lock Class is not explained too much here , It mainly depends on the inside 4 A way :
lock(): Lock
unlock(): Unlock
tryLock(): Attempt to acquire lock , Return to one boolean value
tryLock(long,TimeUtil): Attempt to acquire lock , Timeout can be set Synchronized Only locks are associated with one condition ( Get lock or not ) Related to , inflexible , later Condition And Lock The combination of solves this problem .
When multiple threads compete for a lock , The remaining threads that don't get locks can only keep trying to get locks , Without interrupting . High concurrency leads to performance degradation .ReentrantLock Of lockInterruptibly() Method can give priority to responding to interrupts . A thread waits too long , It can interrupt itself , then ReentrantLock Respond to this interrupt , No longer let this thread wait . With this mechanism , Use ReentrantLock It won't be like synchronized That creates a deadlock .
ReentrantLock Is a common class , It is a reentrant mutex Lock, It has with use synchronized Methods have the same basic behavior and semantics as implicit monitor locks accessed by statements , But it's more powerful .
Use @guardedby Synchronize annotations
@GuardedBy( "this" )Protected by the internal lock of the object@GuardedBy( "fieldName" )Receive and fieldName Reference the associated lock protection@GuardedBy( "ClassName.fieldName" )Subject to the static of a class field The lock is saved@GuardedBy( "methodName()" )The lock object is methodName() Return value of method , Protected by this lock@GuardedBy( "ClassName.class" )suffer ClassName Direct lock object protection of class , Instead of the lock object of an instance of this class
边栏推荐
- Seven marketing strategies of NFT project
- [untitled]
- B+ tree~
- [notes for question brushing] specified interval reversal in the linked list
- 面试官:程序员,请你告诉我是谁把公司面试题泄露给你的?
- ThinkPHP high imitation blue cloud disk system program
- 【刷题笔记】从链表中删去总和值为零的连续节点
- 大页内存原理及使用设置
- Error reporting: SQL syntax error in flask. Fields in SQL statements need quotation marks when formatting
- 一元函数积分学之1__不定积分
猜你喜欢

Visual full link log tracking

Talk about the cross end technical scheme

状态压缩dp-蒙德里安的梦想

【idea】查询字段使用位置

消费行业数字化升级成“刚需”,weiit新零售SaaS为企业赋能!

Seven SQL performance optimizations that spark 3.0 must know

Flask reports an error: pymysq1.err OperationalError:(1054, “Unknown column ‘None‘ in ‘field list‘“)
![[untitled]](/img/28/db3b2e1985dc9acf41cdf2004ea0d5.png)
[untitled]

Seven marketing strategies of NFT project

Classification prediction | MATLAB realizes time series classification prediction of TCN time convolution neural network
随机推荐
【mysql】字符串转int
【树莓派】widows电脑如何与树莓派连接
Wechat campus bathroom reservation applet graduation design finished product (8) graduation design thesis template
C language bracket matching (stack bracket matching C language)
20220728-不纯为数字的字符串排序
【Leetcode-滑动窗口问题】
MySQL stored procedure realizes the creation of a table (copy the structure of the original table and create a new table)
Charles -- 从0-1教你如何使用抓包工具
IT硬件故障的主要原因和预防的最佳实践
Visual full link log tracking
ActiveMQ basic details
State compression DP Mondrian's dream
solidity实现智能合约教程(5)-NFT拍卖合约
“index [hotel/jXLK5MTYTU-jO9WzJNob4w] already exists“
SDRAM Controller Design (two design methods of digital controller)
How to create a custom 404 error page in WordPress
如何处理项目中的时间、范围和成本限制?
[notes for question brushing] binary linked list to integer
Wechat campus bathroom reservation applet graduation design finished product (5) assignment
SystemVerilog-连接和复制运算符