Question: Deadlock occurs when no processing can occur because two processes that are waiting for each other to finish. For example, imagine that two processes need

Deadlock occurs when no processing can occur because two processes that are waiting for each other to finish. For example, imagine that two processes need access to a file or database table row in order to complete, but both processes are attempting to access that resource at the same time. Neither process can complete without the other releasing access to the required resource, so the result is deadlock.

Read and analyze code in the linked document that spawns two different threads at the same time.

1. Predict the results of executing the program.

2. Identify whether a deadlock or starvation event will occur and, if so, at what point in the code.

Here is the code:

Analyzing a Multithreaded Program

/**********************************************************************

* Program: Week 4 Analyze a Multithreaded Program

* Purpose: Review the code and predict the results for the program execution.

* Programmer: Iam A. student

* Instructor: xxx

***********************************************************************/

Package example deadlk;

public class Deadlock {

public static Object Lock1 = new Object(); // aacquires lock on the Lock1 object

public static Object Lock2 = new Object(); // aacquires lock on the Lock2 object

public static void main(String args[]) {

ThreadDemo1 T1 = new ThreadDemo1(); // define the new threads

ThreadDemo2 T2 = new ThreadDemo2(); // and set name for the threads

T1.start();

T2.start();

}

private static class ThreadDemo1 extends Thread {

public void run() {

synchronized (Lock1) {

// synchronized Lock1 and Lock 2 will hold the thread until release

System.out.println("Thread 1: Holding lock 1...");

try { Thread.sleep(10); } // pause for 10 secs, then access thread

catch (InterruptedException e) {} // if exception happens, catch it

System.out.println("Thread 1: Waiting for lock 2..."); // display wait condition

synchronized (Lock2) {

System.out.println("Thread 1: Holding lock 1 & 2...");

}

}

}

}

private static class ThreadDemo2 extends Thread {

public void run() {

synchronized (Lock2) {

System.out.println("Thread 2: Holding lock 2...");

try { Thread.sleep(10); } // pause for 10 secs, then access thread

catch (InterruptedException e) {} // if exception happens, catch it

System.out.println("Thread 2: Waiting for lock 1..."); // display wait condition

synchronized (Lock1) {

System.out.println("Thread 2: Holding lock 1 & 2...");

}

}

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!