Use an AtomicInteger
which is implemented using CAS.
AtomicInteger
has an incrementAndGet()
method you can use for this purpose.
It is also useful to know that there are more Atomic*
variants in the JDK, so there is also AtomicLong
if Integer
is not enough for you.