Java prgroam. SyncDemo adds 1000 to global variable sum using 1000 SumTask threa
ID: 3573361 • Letter: J
Question
Java prgroam. SyncDemo adds 1000 to global variable sum using 1000 SumTask threads as follows:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SyncDemo {
private Integer sum = new Integer(0);
public static void main(String[] args) {
SyncDemo test = new SyncDemo();
System.out.println("What is sum ? " + test.sum);
}
public SyncDemo() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i < 1000; i++) {
executor.execute(new SumTask());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
class SumTask implements Runnable {
public void run() {
int value = sum.intValue() + 1;
sum = new Integer(value);
}
}
}
1. Will sum always add up to 1000 upon a termination of SyncDemo? If sum is not 1000 upon the termination
of SyncDemo, what might be a possible scenario?
2. If sum is not 1000, how can we fix the problem? Please rewrite SyncDemo so that sum always adds up
to 1000
Explanation / Answer
1. The Sum will not be 1000 always because the system initializes the threads at the same time, so it gives the output "0" until the task gets executed, It depends on the system memory, architechture and processor speed. That is the reason we get the output some random numbers like 998,997,1000 etc., randomly.
2. We can fix the problem creating a synchronised task for the SumTask. The program will be as follows:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SyncDemo {
//int sum=0;
static int sum =0;
public static void main(String[] args) {
SyncDemo test = new SyncDemo();
System.out.println("What is sum ? " + test.sum);
}
public synchronized static void test(){
sum++;
}
public SyncDemo() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i <1000; i++) {
executor.execute(new SumTask());
}
executor.shutdown();
while (!executor.isTerminated()) {
}
}
class SumTask implements Runnable {
public void run() {
test();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.