How to implement auto incrementor in multithreaded application in java ?

Use the following code to auto increment a value in a multi threaded application.

public class AutoIncrementor
{
        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.

Search