Question
Check out the following Java class. What do you think the writer of this code wanted the output to be? public class Counting { public
Check out the following Java class.
-
What do you think the writer of this code wanted the output to be?
public class Counting {
public static void main(String[] args) throws InterruptedException{
class Counter {
private int count = 0;
public void increment() { count++; }
public int getCount() {return count; }
}
final Counter counter = new Counter();
class CountingThread extends Thread {
public void run() {
for (int x = 0; x < 10000; x++) {
counter.increment();
}
}
}
CountingThread t1 = new CountingThread();
CountingThread t2 = new CountingThread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.getCount());
}
}
The solution to this problem of differing outputs is to synchronize access to count, and one way to do so is to use the intrinsic lock that comes built into every Java object by making increment() and getCount() synchronized:
class Counter {
private int count = 0;
public synchronized void increment() { ++count; }
public synchronized int getCount() {return count; }
}
Add the above changes to your own code, and then run the program another five times.
-
What is the output for each of the five times you ran the code?
-
Why are the outputs now the same? To answer, provide a detailed description of what it means in Java for these methods to be synchronized.
-
Read the Java documentation for AtomicInteger. Which method in this class is functionally equivalent to count++ in the Counting class above?
Re-write the Counting class to use java.util.concurrent (you should remove the Counter class, and use an AtomicInteger and any appropriate method instead of an intrinsic lock). Paste your code and output.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started