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?
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.
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