Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Consumer that counts how many times it was called?

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.

like image 794
gvlasov Avatar asked May 15 '14 16:05

gvlasov


2 Answers

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.

like image 155
Adam Arold Avatar answered Sep 19 '22 00:09

Adam Arold


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.

like image 38
Michal Gruca Avatar answered Sep 22 '22 00:09

Michal Gruca