Use the following code to auto increment a value in a multi threaded application.
{
private static long maxValue = Long.MAX_VALUE;
private static AtomicLong currentValue = new AtomicLong(100);
public static long getNextValue()
{
if(currentValue.get()==maxValue)
currentValue=new AtomicLong(100);
return currentValue.incrementAndGet();
}
public static void main(String[] args)
{
for(int j=0;j<30;j++)
{
System.out.println(AutoIncrementor.getNextValue());
}
}
}
The above code uses Java concurrency api class AtomicLong to increment and get a value every time getNextValue() method is called.
This avoids the use of synchronized keyword as in previous releases of java.