Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use AtomicInteger as a substitute for mutable Integer?

I have following kind of scenario: It is simple form of code that I am showing here to clarify my concern:

public void callMe()
{
 AtomicInteger howManyOdds = new AtomicInteger(0);
 AtomicInteger howManyEvens = new AtomicInteger(0);
 loopThrough(100,howManyOdds,howManyEvens);
 System.out.println(howManyOdds.get()+" "+howManyEvens.get());
}
private void loopThrough(int counter,AtomicInteger howManyOdds,AtomicInteger howManyEvens)
{
 for(int i = 1 ; i <= counter ;i++)
 {
  if(i%2 == 0)
  howManyEvens.getAndAdd(1);
  else
  howManyOdds.getAndAdd(1);
 }
}

I know that it can be done by int[] but it looks kind of odd. Is AtomicInteger a good substitute for Mutable Integer in such kind of cases? If No then WHY?

like image 539
Mac Avatar asked Mar 20 '23 20:03

Mac


1 Answers

I do not think this is a good idea: using AtomicInteger in contexts that are not inherently concurrent is misleading to the reader.

Using an array is not a good idea, either, even though technically it works well. The problem is that the resultant code is not too descriptive, in the sense that the "mapping" of indexes to their meanings (i.e. 0 -> odd, 1 -> even) is not visible from the API itself.

You would be better off with a mutable class that holds two properties:

public class OddEven {
    int odd, even;
    public int getOdd() {return odd;}
    public int getEven() {return even;}
    public void incOdd() {odd++;}
    public void incEven() {even++;}
}

This achieves a very good readability, without creating a false impression that something concurrent is going on behind the scene.

like image 73
Sergey Kalinichenko Avatar answered Apr 06 '23 04:04

Sergey Kalinichenko