Mark Mark - 1 month ago 11
Java Question

Modular increment with Java's Atomic classes

I was surprised that Java's AtomicInteger and AtomicLong classes don't have methods for modular increments (so that the value wraps around to zero after hitting a limit).

I figure I've got to be missing something obvious. What's the best way to do this?

For example, I want to share a simple int between threads, and I want each thread to be able to increment it, say, mod 10.

I can create a class which uses synchronization/locks, but is there a better, easier way?

Answer

What's difficult about adding a synchronized modifier or block to your addModular() method?

The reason why the Atomic classes don't have this functionality is that they're based on specific atomic hardware instructions offered by current CPUs, and modular arithmetic cannot be implemented by those without resorting to locking or other more complex and potentially inefficient algorithms like the one suggested by matt.