Why isn`t 1 1 a possible solution ; i read the explanation but i want super slow motion to understand this
thanks
This is a straight forward implementation on an thread unsafe class. Observe that count is a shared resource that is accessed by multiple threads and there are multiple issues in this code:
1. Since access to count is not synchronized, there is no guarantee that changes made by thread 1 will even be visible to thread 2. Thus, both the threads may print 0 and increment it to 1 even if they run one after the other. To understand this point, you need to read about topic of visibility guarantee provided by the Java memory model.
public class Counter {
private int count;
public void increment(){
System.out.println(count++);
}
}
If two threads call the increment() method on the same Counter instance simultaneously, which of the following are possible outputs? (Assume that there are no other calls to the Counter instance.)
Scenario 1
Thread 1: Retrieve count. Print count; output is 0.
Thread 2: Retrieve count. Print count; output is 0.
Thread 1: Increment retrieved value; result is 1.
Thread 2: Increment retrieved value; result is 1.
Thread 1: Store result in count; count is now 1.
Thread 2: Store result in count; count is now 1.
Scenario 2
Thread 1: Retrieve count. Print count; output is 0.
Thread 1: Increment retrieved value; result is 1.
Thread 2: Retrieve count. Print count; output is 0.
Thread 1: Store result in count; count is now 1.
Thread 2: Increment retrieved value; result is 1.
Thread 2: Store result in count; count is now 1.
Scenario 3
Thread 1: Retrieve count. Print count; output is 0.
Thread 1: Increment retrieved value; result is 1.
Thread 1: Store result in count; count is now 1.
Thread 2: Retrieve count. Print count; output is 1.
Thread 2: Increment retrieved value; result is 2.
Thread 2: Store result in count; count is now 2.
Hi,
I still cant understand how one result might be 0 as in any case the final asignment to count will be at least 1:
count = 0
temp = count +1 (temp =1)
count = temp.
I would like to add to this.
The output would be option B and D i.e 1 1 and 1 2 if and only if count is pre-incremented
public void increment(){
System.out.println(++count);
}