Sequence Generator
This is really a toy example with the use of the synchronized keyword.
The Sequence Generator is supposed to maintain a counter and return its value and increment it by 1 every time the getNext method is called.
One might use the ++ operator and carelessly fail to put the synchronized keyword for the method. The problem is that the ++ operator is not atomic so the following scenario is possible.
Thread A Read Counter as 10 Increment counter to 11 Update counter as 11
Thread B Read Counter as 10 Increment counter to 11 Update counter as 11
So, in the end we see that the counter has been incremented only once after two calls to getNext, and of course both the calls have returned the same value.
This problem is easily fixed by including the synchronized keyword in the method.
This example also demonstrates how to run a crude test for concurrency. If you leave out the synchronized keyword and run it the final counter value may not be what is expected. But the test is not guaranteed to detect problems.
https://github.com/eipione/java-algos/blob/master/src/main/java/com/ephipi/threads/demo/SequenceGen.java









