Java – is it a good habit to use atomicinteger as an alternative to variable integers?

I have the following situations:

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 it can be done with int [], but it looks strange In this case, is atomicinteger a good substitute for mutable integer? If not, why?

Solution

I don't think this is a good idea: using atomicinteger in a context of non inherent concurrency will mislead readers

Using arrays is not a good idea, even if technically it works well The problem is that the resulting code is not very descriptive because the "mapping" between the index and its meaning (i.e. 0 – > odd, 1 – > even) is not visible in the API itself

It is better to use a mutable class with 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 very good readability without giving the wrong impression that concurrent events occur behind the scene

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>