Вопрос

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.

For testing purposes where you know that access is single-threaded, a quick and dirty workaround is:

int[] i = new int[]{0};
Consumer<Object> handler = o -> i[0]++;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top