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

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...
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'; } }
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...
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:...
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...
IN JAVA PROGRAMMING Write a complete Java program to do the following: a) Prompt the user...
IN JAVA PROGRAMMING Write a complete Java program to do the following: a) Prompt the user to enter the name of the month he/she was born in (example: September). b) Prompt the user to enter his/her weight in pounds (example: 145.75). c) Prompt the user to enter his/her height in feet (example: 6.5). d) Display (print) a line of message on the screen that reads as follows: You were born in the month of September and weigh 145.75 lbs. and...
Write a program in JAVA to create the move set of a Pokémon, and save that...
Write a program in JAVA to create the move set of a Pokémon, and save that move set to a file. This program should do the following: Ask for the pokemon’s name. Ask for the name, min damage, and max damage of 4 different moves. Write the move set data into a file with the pokemon’s name as the filename. The format of the output file is up to you, but keep it as simple as possible
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only run if the account status is active. You can do this adding a Boolean data member ‘active’ which describes account status (active or inactive). A private method isActive should also be added to check ‘active’ data member. This data member is set to be true in the constructor, i.e. the account is active the first time class Account is created. Add another private method...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT