I need (mostly for testing purposes) to write a consumer whose purpose is to remember how many times it was called. However, I can't do
int i = 0;
Consumer<Object> handler = o -> i++;
because i
must be final, and I can't increment final variables. I suppose I need something like MutableInteger
class. What is the right way to count then? Writing my own new class or a new method just for that wouldn't count for a right way.
Use an AtomicInteger
which is implemented using CAS.
AtomicInteger
has an incrementAndGet()
method you can use for this purpose.
It is also useful to know that there are more Atomic*
variants in the JDK, so there is also AtomicLong
if Integer
is not enough for you.
You never could do that. Even with anonymous classes that would not work. You need some object wrapper that will allow you to hold the state, sth like
class NumberOfInvocations {
private int i = 0;
public void increment(){
i +=1;
}
}
but you would have to make sure that everything is thread safe, etc, or you could just use AtomicInteger as suggested by Adam.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With