Question

In: Computer Science

Create a project named Bonus that first demonstrates a race condition using this scenario, then make...

Create a project named Bonus that first demonstrates a race condition using this scenario, then make it thread-safe and show what the execution would look like after your fix.

I need my code to be in java with fully commented

Solutions

Expert Solution

The first class Bonus demonstrates the race condition.

//In this example of race condition in Java multi-threading, we have a shared instance variable. Since there are three threads sharing 
//the same object of the class so the field in the object is shared among the threads. This instance variable c is incremented and decremented so 
//every thread should leave it in the state it initially was i.e. if c is zero in the start, incrementing it will make it 1 and decrementing it will 
//make it zero again.

   public class Bonus implements Runnable{
            private int x = 0;

            public void increment() {
                try {
                    Thread.sleep(10); //sleep(n) induces delay in a specific thread by n ms or ns.
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace(); //printStackTrace() prints the throwable along with the line number and class name where the exception occurred.
                }
                x++;
            }

            public void decrement() {    
                x--;
            }

            public int getValue() {
                return x;
            }
            
            @Override
            public void run() {       //when run() method is called the code inside run() gets executed. calling start() method executes run() method.
                //incrementing
                this.increment();
                System.out.println("The value for Thread After incrementing: " 
                + Thread.currentThread().getName() + " " + this.getValue());
                //decrementing
                this.decrement();
                System.out.println("The value for Thread at the end: " 
                + Thread.currentThread().getName() + " " + this.getValue());        
            }
        }

        class RaceConditionDemo{
            public static void main(String[] args) {
                Bonus bonus = new Bonus();
                Thread t1 = new Thread(bonus, "Thread-1");
                Thread t2 = new Thread(bonus, "Thread-2");
                Thread t3 = new Thread(bonus, "Thread-3");
                t1.start();                     //start() method is used to start the implementation of thread and it also calls the run() method.
                t2.start();
                t3.start();
            }    
        }

The output of the above code shows how the shared variable c gives the wrong values.

Below is a Thread-safe which avoids race-condition in java.

//To fix the race condition we need to have a way to restrict resource access to only one thread at a time. We have to use synchronized keyword to 
//synchronize the access to the shared resource. 

public class Bonus implements Runnable{
    private int x = 0;

    public  void increment() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        x++;
    }

    public  void decrement() {    
        x--;        
    }

    public  int getValue() {
        return x;
    }
    
    @Override
    public void run() {
        //All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. 
        //All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
        
        synchronized(this){
            // incrementing
            this.increment();
            System.out.println("The value for Thread after incrementing: " 
             + Thread.currentThread().getName() + " " + this.getValue());
            //decrementing
            this.decrement();
            System.out.println("The value for Thread at the end: " + Thread.currentThread().getName() 
                + " " + this.getValue());
        }        
    }
}

 class RaceConditionDemo{
    public static void main(String[] args) {
        Bonus counter = new Bonus();
        Thread t1 = new Thread(counter, "Thread-1");
        Thread t2 = new Thread(counter, "Thread-2");
        Thread t3 = new Thread(counter, "Thread-3");
        t1.start();
        t2.start();
        t3.start();
    }    
}

Related Solutions

Create a project charter using Microsoft Word that will be based on the following scenario: Scenario:...
Create a project charter using Microsoft Word that will be based on the following scenario: Scenario: You have just been placed on an IT project management team to develop a Master Patient Index (MPI) system. This 300-bed facility is currently using a paper- based system and is slowly making the transition to electronic systems. The system they want to purchase and manage is an electronic MPI system for the Admissions department. They want this system to be able to be...
Using NetBeans, create a Java project named FruitBasket. Set the project location to your own folder....
Using NetBeans, create a Java project named FruitBasket. Set the project location to your own folder. 3. Import Scanner and Stacks from the java.util package. 4. Create a Stack object named basket. 5. The output shall: 5.1.Ask the user to input the number of fruits s/he would like to catch. 5.2.Ask the user to choose a fruit to catch by pressing A for apple, O for orange, M for mango, or G for guava. 5.3.Display all the fruits that the...
1. CREATE a brief critical incident scenario that demonstrates A. Effective issuing of orders and directions,...
1. CREATE a brief critical incident scenario that demonstrates A. Effective issuing of orders and directions, and B.) Effective Command Presence. 2. IDENTIFY at what specific events, during the created critical incident, where two (2) Acute Critical Stress Symptoms and two (2) Delayed Critical Stress Symptoms are found. Please use and list credible APA resource and cite them, at least two. Thank you
1. CREATE a brief critical incident scenario that demonstrates A. Effective issuing of orders and directions,...
1. CREATE a brief critical incident scenario that demonstrates A. Effective issuing of orders and directions, and B.) Effective Command Presence. 2. IDENTIFY at what specific events, during the created critical incident, where two (2) Acute Critical Stress Symptoms and two (2) Delayed Critical Stress Symptoms are found. Please use and list credible APA resource and cite them, at least two. Thank you
There is an experiment that demonstrates the first law of thermodynamics by using a tin can....
There is an experiment that demonstrates the first law of thermodynamics by using a tin can. The problem is I don't understand why there is a work done. The link to that video is https://youtu.be/jNPUCmkKiE4?list=WL&t=180 . Can someone explain to me why the tin can suddenly imploded?
Create a Visual Studio console project named exercise093. In the exercise093.cpp file first define a function...
Create a Visual Studio console project named exercise093. In the exercise093.cpp file first define a function void lowerToUpper(std::string & sentence) that iterates over all characters in the sentence argument. Any lowercase letter should be converted to uppercase. This can be done by including <cctype> and testing each character in sentence with the islower() function. If islower(sentence[i]) returns true then sentence[i] should be replaced with toupper(sentence[i]). The main() function should assign "Hello how are you doing?" to sentence, call lowerToUpper(sentence), and...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a...
Create a new Java project named Program 4 Three Dimensional Shapes. In this project, create a package named threeDimensional and put all 3 of the classes discussed below in this package Include a header comment to EACH OF your files, as indicated in your instructions. Here's a link describing the header. Note that headers are not meant to be in Javadoc format. Note that Javadoc is a huge part of your grade for this assignment. Javadoc requires that every class,...
Create a scenario that demonstrates specific ways in which management could manipulate transactions impacting inventory values...
Create a scenario that demonstrates specific ways in which management could manipulate transactions impacting inventory values that the auditing team might not detect. Recommend key strategies that the auditor could implement in anticipation of such manipulation. Justify your response. Discuss the difference between a subsequent event and a subsequent discovery of facts. Next, determine the auditor's responsibility for each event after the audit report is completed. Support your position.
Create a scenario that demonstrates specific ways in which management could manipulate transactions impacting inventory values...
Create a scenario that demonstrates specific ways in which management could manipulate transactions impacting inventory values that the auditing team might not detect. Recommend key strategies that the auditor could implement in anticipation of such manipulation
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT