* Write a program which keeps min and max value in threadsafe way
* Support 2 apis
* void updateMaxMin(int val)
* int getMin()
* int getMax()
*
* Solution
* Use compareAndSet method of AtomicInteger to update min and max
public class MinMaxKeeper {
private AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
private AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
/**
* Threadsafe way of updating min and max
* @param value
*/
public void updateMinMax(int value){
//update min
while(true){
//if value is greater than whatever is in min just break right away
int minVal = min.get();
if(value >= minVal){
break;
}
//try to update value only if minVal is in min
boolean isSetSuccesful = min.compareAndSet(minVal, value);
//if set was successful break from while loop else keep looping
if(isSetSuccesful){
break;
}
}
//update max
while(true){
int maxVal = max.get();
if(value <= maxVal){
break;
}
boolean isSetSuccesful = max.compareAndSet(maxVal, value);
if(isSetSuccesful){
break;
}
}
}
public int getMin(){
return min.get();
}
public int getMax(){
return max.get();
}
}
* Support 2 apis
* void updateMaxMin(int val)
* int getMin()
* int getMax()
*
* Solution
* Use compareAndSet method of AtomicInteger to update min and max
public class MinMaxKeeper {
private AtomicInteger min = new AtomicInteger(Integer.MAX_VALUE);
private AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
/**
* Threadsafe way of updating min and max
* @param value
*/
public void updateMinMax(int value){
//update min
while(true){
//if value is greater than whatever is in min just break right away
int minVal = min.get();
if(value >= minVal){
break;
}
//try to update value only if minVal is in min
boolean isSetSuccesful = min.compareAndSet(minVal, value);
//if set was successful break from while loop else keep looping
if(isSetSuccesful){
break;
}
}
//update max
while(true){
int maxVal = max.get();
if(value <= maxVal){
break;
}
boolean isSetSuccesful = max.compareAndSet(maxVal, value);
if(isSetSuccesful){
break;
}
}
}
public int getMin(){
return min.get();
}
public int getMax(){
return max.get();
}
}