Sequential numbers, talk to any Domino developer and they will shudder when you bring up the subject. They are one of the hardest things to implement in a Domino application. There are many suggestions on how to do sequential numbers in domino apps and they all have advantages and disadvantages.
One of the most common ways is to use an agent which allows for documents to replicate to a central location before assigning them their number. The main problem with this approach is that the numbers don’t get assigned till a later time and the users of the application will more then likely need the number immediately.
Another method involves using profile documents but this can fail because profile documents are cached on each users computer and it is even worse for web based applications because each HTTP thread has its own cache so even users on the same server generating sequential numbers could end up with a duplicate number.
With XPages, however, they way be a solution but before I go into details I’ll stress that this is not a perfect solution because it is designed for a single application running on a single server and not for a replicated application.
In SSJS in XPages there is a feature called ‘synchronized’. Any code inside a synchronized code block will only execute once at a time. If two people in two different sessions click on a button that runs the SSJS at the same time then whichever thread hits the SSJS code first will start running the synchronized block first while the other persons thread will wait till the first persons thread has finished and then once the first persons thread has finished the second persons thread will run the synchronized block of SSJS. Think of it as a car wash, it’s only possible to wash one car at a time while all the other cars that need to use the car wash will queue up outside waiting for the car in front of them to be finished.
Here is a simple version of the code that I built, In my final version I broke out the initial loading and saving of the number store document into separate functions so that I didn’t have to repeat the code multiple times. The code below is simplified for demo reasons.