当前位置:网站首页>Thread deadlock and its solution

Thread deadlock and its solution

2022-06-12 09:15:00 Java supernatural Road

Four necessary conditions for thread deadlock

If the following four conditions are true in a system , Then it can cause a deadlock :

  1. Mutual exclusivity : The possession of resources by threads is exclusive , A resource can only be occupied by one thread , Until released .
  2. Request and hold conditions : When a thread blocks a resource that is requested to be occupied , Don't release the acquired resources .
  3. Not to deprive : Before a thread releases resources , Other threads cannot be deprived of occupation .
  4. Loop waiting for : When you have a life and death lock , Thread goes into a dead loop , Permanent blocking .

resolvent :

  1. Mutual exclusivity , You can use ThreadLocal
  2. Request and hold conditions , Kick one out ( End one )
  3. Not to deprive ,trylcok, Add a timeout , Unable to seize and release resources

Distributed lock , It can be used DB,redis Of nx Implement distributed locks

DB Distributed lock
1、 Generate... According to the business field transaction_id, And thread safe creation of lock resources
2、 according to transaction_id To apply for the lock
3、 Release the lock

Threads within a process can be based on obj To synchronize .obj In this case, it can be understood as a lock object . If the thread wants to enter synchronized In code block , Must hold first obj A lock on an object . This kind of lock is JAVA The built-in lock inside , The creation process is thread safe . Then with the help of DB, How to ensure that the process of creating a lock is thread safe ? You can use DB Medium UNIQUE
KEY characteristic , Once there's a repeat key, because UNIQUE
KEY Uniqueness , Will throw an exception . stay JAVA Inside , yes SQLIntegrityConstraintViolationException abnormal .

原网站

版权声明
本文为[Java supernatural Road]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010531103337.html