What causes deadlock? How to avoid it?

⭐Column introduction

This column will continue to update various questions about JAVA, including interview questions, JAVA introduction to proficiency, etc.

The update speed is maintained at 3-5 articles per day
Insert image description here

Problem Description

What causes deadlock? How to avoid it?

Insert image description here

Answer

Deadlock refers to a deadlock state caused by multiple processes or threads competing for system resources in a concurrent system, and each other is unable to continue executing. The principle of deadlock can be summarized as the following four necessary conditions being met simultaneously:

Mutually exclusive condition: The resource can only be occupied by one process or thread and cannot be accessed by other processes or threads at the same time.
Possessing and waiting conditions: A process or thread occupies some resources and requests other resources, but does not release the occupied resources while waiting for other resources.
Inevitability condition: A resource that has been allocated to a process or thread cannot be forcibly preempted and can only be explicitly released by the process or thread that owns the resource.
Loop waiting condition: There is a resource demand chain of a process or thread, forming a closed loop.

In order to avoid deadlock, you can take the following methods:

Break the mutual exclusion condition: Change some resources to be shareable, that is, multiple processes or threads can access them at the same time.
Destruction of occupied and waiting conditions: requires a process or thread to release the occupied resources when requesting resources, and does not hold any resources while waiting.
Breaking inalienable conditions: Allows the system to forcefully reclaim certain resources and allocate them to other processes or threads.
Destroy circular waiting conditions: Sort resources and require processes or threads to apply for resources in a certain order to avoid circular waiting.

Guess you like

Origin blog.csdn.net/weixin_50843918/article/details/133046793
Recommended