views:

130

answers:

2

I'm looking to create a simple web service that when polled returns a unique id. The ID has to be human readable (i.e. not a guid, probably in the form 000023) and is simply incremented by 1 each time its called.

Now I need to consider that it may be called by two different applications at the same time and I don't want it to return the same number to each application.

Is there another option than using a database to store the current number?

Surely this has been done before, can anyone point me at some source code if it is.

Thanks,

Neil

A: 

you can use a file.

Pseudocode:

if (!locked('counter.txt'))
   counter = read('counter.txt')
else
   wait
   startAgain
lock('counter.txt')
counter++
print counter
write('counter.txt', counter)
unlock('counter.txt)
neo
A: 

Use a critical section piece of code to control flow one at a time through a section of code. You can do this using the lock statement or by being slightly more hardcore and using a mutex directly. Doing this will ensure that you return a different number to each caller.

As for storing it, using a database is overkill for returning an auto incrementing number - although SQLServer and Oracle (and most likely others but i can't speak for them) both provide an auto incrementing keys feature, so you could have the webservice called, generate a new entry in the database table, return the key, and the caller can use that number as a key back to that record (if you are saving more data later after the initial call). This way you also let the database worry about the generation of unique numbers, you don't have to worry about the details of it - although this is not a good option if you don't already have a database.

The other option is to store it in a local file, although that would be expensive to read the file, increment the number, and write it back out, all within a critical section.

slugster
This will be used by different applications so I won't be creating rows with data. The sole purpose of the service is to provide a unique incremented number. There will be access to a database if required. It just seems strange to me to have a table with only one value (the incrementing number).
Neil
If you already have a database available then this is the best (and fastest) option. It's not so strange - you are just leveraging one of the features of the database.
slugster