In: Computer Science
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?
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());
}
}