How can we use AtomicInteger for limited sequence generation say the sequence number has to be between 1 to 60. Once the sequence reaches 60 it has to start again from 1. I wrote this code though not quite sure wether this is thread safe or not?
public int getNextValue()
{
int v;
do
{
v = val.get();
if ( v == 60)
{
val.set(1);
}
}
while (!val.compareAndSet(v , v + 1));
return v + 1;
}
As of Java 8, you can use
AtomicInteger.updateAndGet:Another alternative would be to simply do…
…unless you’re concerned with exceeding the integer max-value (2147483647). If that is a concern, you could have a look at the
getAndIncrementimplementation:All you need to change is the
int next...line to something like:Oops. This loops through 0->59. You needed 1->60, so add one to the return-value to get the desired result.