Câu hỏi phỏng vấn Concurrency
Câu hỏi

What is a Deadlock?

Câu trả lời

A deadlock is a situation in concurrent computing where two or more processes or threads are unable to proceed because each is waiting for the other to release a resource. This results in a standstill where none of the processes can continue execution. Deadlocks are a common problem in multiprocessing systems, parallel computing, and distributed systems, where resources such as locks, semaphores, or other synchronization mechanisms are used to manage access to shared resources.

Necessary Conditions for Deadlock

For a deadlock to occur, the following four conditions must be met simultaneously:

  1. Mutual Exclusion: At least one resource must be held in a non-sharable mode, meaning only one process can use the resource at any given time.
  2. Hold and Wait: A process must be holding at least one resource and waiting to acquire additional resources that are currently being held by other processes.
  3. No Preemption: Resources cannot be forcibly taken away from a process; they must be released voluntarily by the process holding them.
  4. Circular Wait: A set of processes must exist such that each process is waiting for a resource held by the next process in the set, forming a circular chain.

Example in Java

In Java, deadlocks often occur in multithreaded applications where multiple threads need the same locks but acquire them in different orders. Here is a simple example:

java Copy
public class DeadlockExample {
    public static Object Lock1 = new Object();
    public static Object Lock2 = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                synchronized (Lock1) {
                    System.out.println("Thread 1: Holding lock 1...");
                    try { Thread.sleep(10); } catch (InterruptedException e) {}
                    System.out.println("Thread 1: Waiting for lock 2...");
                    synchronized (Lock2) {
                        System.out.println("Thread 1: Holding lock 1 & 2...");
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                synchronized (Lock2) {
                    System.out.println("Thread 2: Holding lock 2...");
                    try { Thread.sleep(10); } catch (InterruptedException e) {}
                    System.out.println("Thread 2: Waiting for lock 1...");
                    synchronized (Lock1) {
                        System.out.println("Thread 2: Holding lock 1 & 2...");
                    }
                }
         ...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

What is a Data Race?

senior

What are some advantages of Lockless Concurrency?

middle

What is a Race Condition?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào