Question

In: Computer Science

Java programming: Save the program as DeadlockExample.java   Run the program below.  Note whether deadlock occurs.  Then modify the...

Java programming:

Save the program as DeadlockExample.java  

Run the program below.  Note whether deadlock occurs.  Then modify the program to add two more threads: add a class C and a class D, and call them from main.  Does deadlock occur?

import java.util.concurrent.locks.*;

class A implements Runnable

{

            private Lock first, second;

            public A(Lock first, Lock second) {

                        this.first = first;

                        this.second = second;

            }

            public void run() {

                        try {

                                    first.lock();

                                    System.out.println("Thread A got first lock.");

                                    // do something

                                    try {

                                                Thread.sleep( ((int)(3*Math.random()))*1000);

                                    }

                                    catch (InterruptedException e) {}

                                    second.lock();

                                    System.out.println("Thread A got second lock.");

                                    // do something

                        }

                        finally {

                                    first.unlock();

                                    second.unlock();

                        }

            }

}

class B implements Runnable

{

            private Lock first, second;

            public B(Lock first, Lock second) {

                        this.first = first;

                        this.second = second;

            }

            public void run() {

                        try {

                                    second.lock();

                                    System.out.println("Thread B got second lock.");

                                    // do something

                                    try {

                Thread.sleep( ((int)(3*Math.random()))*1000);

                                    }

                                    catch (InterruptedException e) {}

                                    first.lock();

                                    System.out.println("Thread B got first lock.");

                                    // do something

                        }

                        finally {

                                    second.unlock();

                                    first.unlock();

                        }

            }

}

public class DeadlockExample

{

            public static void main(String arg[]) {

                        Lock lockX = new ReentrantLock();

                        Lock lockY = new ReentrantLock();

                        Thread threadA = new Thread(new A(lockX,lockY));

                        Thread threadB = new Thread(new B(lockX,lockY));

                        threadA.start();

                        threadB.start();

                        System.out.println("Deadlock!!!!");

            }

}

Solutions

Expert Solution

Yes deadlock occurs but with with a warning that max real time limit exceeded as the output below shows:

Code:

import java.util.concurrent.locks.*;
import java.io.*;

class A implements Runnable

{

    private Lock first, second, third1, fourth1;

    public A(Lock first, Lock second, Lock third1, Lock fourth1) {

        this.first = first;

        this.second = second;

        this.third1 = third1;

        this.fourth1 = fourth1;

    }

    public void run() {

        try {

                first.lock();

                System.out.println("Thread A got first lock.");

                // do something

                try {

                        Thread.sleep( ((int)(3*Math.random()))*1000);

                    }

                    catch (InterruptedException e) {}

                    second.lock();
                    third1.lock();
                    fourth1.lock();

                    System.out.println("Thread A got second lock.");
                    System.out.println("Thread A got third lock.");
                    System.out.println("Thread A got fourth lock.");
                    // do something

                }

                finally {

                            first.unlock();
                            second.unlock();
                            third1.unlock();
                            fourth1.unlock();

                        }

        }

}

class B implements Runnable

{

    private Lock first, second, third1, fourth1;

    public B(Lock first, Lock second, Lock third1, Lock fourth1) {

        this.first = first;

        this.second = second;

        this.third1 = third1;

        this.fourth1 = fourth1;

    }

    public void run() {

        try {

                second.lock();

                System.out.println("Thread B got second lock.");

                // do something

                try {

                        Thread.sleep( ((int)(3*Math.random()))*1000);

                    }

                    catch (InterruptedException e) {}

                    first.lock();
                    third1.lock();
                    fourth1.lock();

                    System.out.println("Thread B got first lock.");
                    System.out.println("Thread B got third lock.");
                    System.out.println("Thread B got fourth lock.");
                    // do something

                }

                finally {

                            second.unlock();
                            first.unlock();
                            third1.unlock();
                            fourth1.unlock();

                        }

        }

}

class C implements Runnable

{

    private Lock first, second, third1, fourth1;

    public C(Lock first, Lock second, Lock third1, Lock fourth1) {

        this.first = first;

        this.second = second;

        this.third1 = third1;

        this.fourth1 = fourth1;

    }

    public void run() {

        try {

                third1.lock();

                System.out.println("Thread C got third lock.");

                // do something

                try {

                        Thread.sleep( ((int)(3*Math.random()))*1000);

                    }

                    catch (InterruptedException e) {}

                    first.lock();
                    second.lock();
                    fourth1.lock();

                    System.out.println("Thread A got first lock.");
                    System.out.println("Thread A got second lock.");
                    System.out.println("Thread A got fourth lock.");
                    // do something

                }

                finally {

                            third1.unlock();
                            first.unlock();
                            second.unlock();
                            fourth1.unlock();

                        }

        }

}

class D implements Runnable

{

    private Lock first, second, third1, fourth1;

    public D(Lock first, Lock second, Lock third1, Lock fourth1) {

        this.first = first;

        this.second = second;

        this.third1 = third1;

        this.fourth1 = fourth1;

    }

    public void run() {

        try {

                fourth1.lock();

                System.out.println("Thread C got fourth lock.");

                // do something

                try {

                        Thread.sleep( ((int)(3*Math.random()))*1000);

                    }

                    catch (InterruptedException e) {}

                    first.lock();
                    second.lock();
                    third1.lock();

                    System.out.println("Thread A got first lock.");
                    System.out.println("Thread A got second lock.");
                    System.out.println("Thread A got third lock.");
                    // do something

                }

                finally {

                            fourth1.unlock();
                            first.unlock();
                            second.unlock();
                            third1.unlock();

                        }

        }

}


public class Main

{

    public static void main(String arg[]) {

        Lock lockA = new ReentrantLock();

        Lock lockB = new ReentrantLock();
        
        Lock lockC = new ReentrantLock();

        Lock lockD = new ReentrantLock();

        Thread threadA = new Thread(new A(lockA,lockB, lockC, lockD));

        Thread threadB = new Thread(new B(lockA,lockB, lockC, lockD));
        
        Thread threadC = new Thread(new C(lockA,lockB, lockC, lockD));

        Thread threadD = new Thread(new D(lockA,lockB, lockC, lockD));

        threadA.start();

        threadB.start();
        
        threadC.start();
        
        threadD.start();

        System.out.println("Deadlock!!!!");

    }

}

Yes, deadlock occurs!


Related Solutions

Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables   ...
Question: Java Programming. ** Modify Current Program. Current Program class Account{       //instance variables    private long accountNumber;    private String firstName;    private String lastName;    private double balance;       //constructor    public Account(long accountNumber, String firstName, String lastName, double balance) {        this.accountNumber = accountNumber;        this.firstName = firstName;        this.lastName = lastName;        this.balance = balance;    }    //all getters and setters    public long getAccountNumber() {        return...
Your task is to modify the program from the Java Arrays programming assignment to use text...
Your task is to modify the program from the Java Arrays programming assignment to use text files for input and output. I suggest you save acopy of the original before modifying the software. Your modified program should: contain a for loop to read the five test score into the array from a text data file. You will need to create and save a data file for the program to use. It should have one test score on each line of...
Complete the java program. /* Note: Do not add any additional methods, attributes. Do not modify...
Complete the java program. /* Note: Do not add any additional methods, attributes. Do not modify the given part of the program. Run your program against the provided Homework2Driver.java for requirements. */ /* Hint: This Queue implementation will always dequeue from the first element of the array i.e, elements[0]. Therefore, remember to shift all elements toward front of the queue after each dequeue. */ public class QueueArray<T> { public static int CAPACITY = 100; private final T[] elements; private int...
Basic JAVA Question When we try to run this program, a problem occurs. What is this...
Basic JAVA Question When we try to run this program, a problem occurs. What is this problem called? And why does this problem occur here? public class Main {    public static void main(String[] args) {    PhoneNumber pn = new PhoneNumber();        System.out.println(pn.isTollFree());    } } class PhoneNumber { String number;    public boolean isTollFree() { return number.charAt(1) == '8'; } }
can someome investigate my program that utilizes semaphores that can result in deadlock due to programming...
can someome investigate my program that utilizes semaphores that can result in deadlock due to programming errors and help in finding out if the solution meet all criteria for the critical section If yes, then comment code identifying the parts of code that do If no, could you help in fixing the code wherever given solution fails criteria in the code below #include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <unistd.h> #define N 5 #define THINKING 2 #define HUNGRY 1 #define...
Complete all parts of this java program. Use Homework2Driver.java below for testing. /* Note: Do not...
Complete all parts of this java program. Use Homework2Driver.java below for testing. /* Note: Do not add any additional methods, attributes. Do not modify the given part of the program. Run your program against the provided Homework2Driver.java for requirements. */ public class Node<T> { private T info; private Node nextLink; public Node(T info) { } public void setInfo(T info) { } public void setNextLink(Node nextNode) { } public T getInfo() { } public Node getNextLink() { } } /* Note:...
Program: Java Write a Java program using good programming principles that will aggregate the values from...
Program: Java Write a Java program using good programming principles that will aggregate the values from several input files to calculate relevant percentages and write the values to an output file. You have been tasked with reading in values from multiple files that contains different pieces of information by semester. The Department of Education (DOE) would like the aggregate values of performance and demographic information by academic year. A school year begins at the fall semester and concludes at the...
Program: Java Write a Java program using good programming principles that will aggregate the values from...
Program: Java Write a Java program using good programming principles that will aggregate the values from several input files to calculate relevant percentages and write the values to an output file. You have been tasked with reading in values from multiple files that contains different pieces of information by semester.    The Department of Education (DOE) would like the aggregate values of performance and demographic information by academic year. A school year begins at the fall semester and concludes at the...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the...
Java Programming For this assignment, you should modify only the User.java file. Make sure that the InsufficientFundsException.java file is in the same folder as your User.java File. To test this program you will need to create your own "main" function which can import the User, create an instance and call its methods. One of the methods will throw an exception in a particular circumstance. This is a good reference for how throwing exceptions works in java. I would encourage you...
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT