Fast response, not thread safe. The test and set must be atomic, unless you synchronize the whole method. Pay attention to val.get (), and checking v is not atomic. If the stream is issued after v = val.get (), you will receive two calls with the same sequence number.
Also, if compareAndSet fails, you never change the value, it will be an infinite loop.
AtomicInteger has a getAndIncrement () call. This will give you the net return value.
Gliding is a little trickier. One solution is to change the return value. Something like that:
int v = val.getAndIncrement(); return (v % 60) + 1;
Since each thread has a local copy of v, we can safely do some math and return a value. If you get overflow, there is one sticking point. Depending on how often you generate the sequence number, this may or may not be a problem.
Paul rubel
source share