Question

In: Computer Science

class Counter{   private int count = 0;   public void inc(){    count++;     }   public int get(){     return...

class Counter{

  private int count = 0;

  public void inc(){

   count++;  

  }

  public int get(){

    return count;

  }

}

class Worker extends Thread{

Counter count;

  Worker(Counter count){

    this.count = count;

  }

  public void run(){

    for (int i = 0; i < 1000;i++){

      synchronized(this){

        count.inc();

      }}

  }

}

public class Test

{  

  public static void main(String args[]) throws InterruptedException

  {

    Counter c = new Counter();

    Worker w1 = new Worker(c);

    Worker w2 = new Worker(c);

    w1.start();

    w2.start();

    w1.join();

    w2.join();

    System.out.println(c.get());

     

  }

}

The above code should print 2000 because inc() method is synchronized. However, it is printing a different number ranging from 1000 to 2000 everytime it runs. Can you explain why? How would you fix it?

Solutions

Expert Solution

This is beacause the inc() method is not synchronized in Counter class. When both threads try to execute count++ simultaneously, there may be an anomaly. Hence we are getting a different answer each time. If we synchronize this method or only the statement inside it, it will print 2000 everytime.

The following code will always print 2000.

class Counter{

private int count = 0;

public void inc(){
synchronized(this){
  
count++;
  
}

}

public int get(){

return count;

}

}

class Worker extends Thread{

Counter count;

Worker(Counter count){

this.count = count;

}

public void run(){

for (int i = 0; i < 1000;i++){

synchronized(this){

count.inc();

}}

}

}

public class Test

{

public static void main(String args[]) throws InterruptedException

{

Counter c = new Counter();

Worker w1 = new Worker(c);

Worker w2 = new Worker(c);

w1.start();

w2.start();

w1.join();

w2.join();

System.out.println(c.get());

}

}


Related Solutions

#include<iostream> using namespace std; class point{ private: int x; int y; public: void print()const; void setf(int,...
#include<iostream> using namespace std; class point{ private: int x; int y; public: void print()const; void setf(int, int); }; class line{ private: point ps; point pe; public: void print()const; void setf(int, int, int, int); }; class rectangle{ private: line length[2]; line breadth[2]; public: void print()const; void setf(int, int, int, int, int, int, int, int); }; int main(){ rectangle r1; r1.setf(3,4,5,6, 7, 8, 9, 10); r1.print(); system("pause"); return 0; } a. Write function implementation of rectangle, line and point. b. What is...
class ArrayReverse1{ public static void reverse(int[] a, int index) { if (index >0) { index= index...
class ArrayReverse1{ public static void reverse(int[] a, int index) { if (index >0) { index= index - 1; // Decrementing the index System.out.printf("%d%n", a[index]); reverse(a, index); // Recursive call } return; } public static void main (String args[]) { int [] array = { 1, 2, 3, 4, 5 }; int n=array.length; reverse(array,n); // function call } } Write a generic version of the corrected recursive reverse method that could be used to print any of the following arrays (or...
public class Clock { private int hr; private int min; private int sec; public Clock() {...
public class Clock { private int hr; private int min; private int sec; public Clock() { setTime(0, 0, 0); } public Clock(int hours, int minutes, int seconds) { setTime(hours, minutes, seconds); } public void setTime(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec =...
1. Consider the following code: public class Widget implements Serializable { private int x; public void...
1. Consider the following code: public class Widget implements Serializable { private int x; public void setX( int d ) { x = d; } public int getX() { return x; } writeObject( Object o ) { o.writeInt(x); } } Which of the following statements is true? I. The Widget class is not serializable because no constructor is defined. II. The Widget class is not serializable because the implementation of writeObject() is not needed. III. The code will not compile...
Given: class Monster {     private:     string name;     int dangerLevel;     public:     Monster(sting, int);     virtual void hunt()
Given: class Monster {     private:     string name;     int dangerLevel;     public:     Monster(sting, int);     virtual void hunt() = 0;     virtual void fight(Monster&);     string getName() const; }; class GiantMonster : public Monster {     protected:         int height;          public:         GiantMonster(string, int, int);         virtual void trample(); }; class Dinosaur : public GiantMonster {     public:     Dinosaur(string, int, int);     void hunt();     void roar(); }; class Kraken : protected GiantMonster {     public:     Kraken(string, int, int);     virtual void hunt();     void sinkShip(); }; Indicate if the code snippets below are...
import javax.swing.JOptionPane; public class Animal {    private int numTeeth = 0;    private boolean spots...
import javax.swing.JOptionPane; public class Animal {    private int numTeeth = 0;    private boolean spots = false;    public int weight = 0;       public Animal(int numTeeth, boolean spots, int weight){        this.numTeeth =numTeeth;        this.spots = spots;        this.weight =weight;    }       public int getNumTeeth(){        return numTeeth;    }    public void setNumTeeth(int numTeeth) {        this.numTeeth = numTeeth;    }       public boolean getSpots() {       ...
public class SinglyLikedList {    private class Node{        public int item;        public...
public class SinglyLikedList {    private class Node{        public int item;        public Node next;        public Node(int item, Node next) {            this.item = item;            this.next = next;        }    }       private Node first;    public void addFirst(int a) {        first = new Node(a, first);    } } 1. Write the method add(int item, int position), which takes an item and a position, and...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the...
public class Problem1 {    public static void partition(int[] A)    {        /*Rearrange the array to have the following property:        Suppose the first element in the original array has the value x.        In the new array, suppose that x is in position i, that is data[i] = x.        Then, data[j] <= x for all j < I and data[j] > x for all j > i.        Thus, informally, all the...
public class StringTools {    public static int count(String a, char c) {          ...
public class StringTools {    public static int count(String a, char c) {           }
public class IntNode               {            private int data;            pri
public class IntNode               {            private int data;            private IntNode link;            public IntNode(int data, IntNode link){.. }            public int     getData( )          {.. }            public IntNode getLink( )           {.. }            public void    setData(int data)     {.. }            public void    setLink(IntNode link) {.. }         } All questions are based on the above class, and the following declaration.   // Declare an empty, singly linked list with a head and a tail reference. // you need to make sure that head always points to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT