public class Counter{
static AtomicInteger ai = new AtomicInteger(0);
public static void increment(){
//1
}
//other valid code }
This class is supposed to keep an accurate count for the number of times the increment method is called. Several classes share this class and call its increment method. What should be inserted at //1 ?
I think there could be 3 valid answers:
1. ai.incrementAndGet();
2. ai.addAndGet(1);
3. ai.set(ai.get()+1); - What is wrong with this option?
Last edited by admin on Tue Oct 07, 2014 7:36 am, edited 1 time in total.
Reason:Scrambled qid
Did you read the explanation provided with the option?
ai.set(ai.get()+1); is not atomic. It is composed of two independent method calls. It is possible for another thread to change the count in between those two calls. That is why it is not valid.
If you like our products and services, please help us by posting your review here.
admin wrote:Did you read the explanation provided with the option?
ai.set(ai.get()+1); is not atomic. It is composed of two independent method calls. It is possible for another thread to change the count in between those two calls. That is why it is not valid.
Hi. That is why I asked here. There was no such explanation.