In: Computer Science
When multiple thread access the setLower and setUpper methods of the NumberRange object, the isValid method return false. Explain why?
public class NumberRange {
private final AtomicInteger lower = new AtomicInteger(0);
private final AtomicInteger upper = new AtomicInteger(0);
public void setLower(int i) {
if(i>lower upper.get()) throw new IllegalArgumentException();
lower.set(i);
}
public void setUpper(int i) {
if (i < lower.get()) throw new IllegalArgumentException();
upper.set(i);
}
public boolean isValid() {
return (lower.get() <= upper.get());
}
}
The setLower method compares the passed value with the upper value, and sets only if given value is less than upper.. Similarly, the setUpper method sets the passed value to upper, only if passed value is more than the lower value.. Now when multiple thread concurrently execute setLower and setUpper methods below situation may occur: Assume start values of lower and upper as: Lower => 100 Upper => 1000 Lets say thread T1 tries to call setLower(500) and thread T2 tries to call setUpper(200) almost at the same time. Suppose execution happens like below: T1 checks if(i>upper.get()), which comes to false, since 500 is lesser than 1000. Hence it do not throws the exception. But then execution goes to T2.. T2 checks if (i < lower.get()), and finds that 200 is more than current lower 100, Hence it also do not throw any exception. It then sets value of upper to 200.. So now, Lower=>100, Upper=>200 Now, Execution goes back to T1, which has already done the error checking and now just sets the lower value to 500.. So, Now: Lower=>500, Upper=>200 Now, if we call isValid function, it will return false, since lower value is more than upper value
**************************************************
Please consider providing a thumbs up to this question.