A static function retUnique() returns a unique value. My question is that if there are many users who are using the same function at a given point of time, what happens? Is there a best practice to make sure that each users accessing this static function simultaneously get a unique value and also do not face threading issues.
Can one give me an example?
Assuming you want to simply return a unique incrementing integer value, the simplest safe approach is probably to use a private static counter and a private static lock object. Something like:
It’s up to you to make sure the particular lock object is used to protect any other access to the static counter member (which is why they are declared private, of course, so the class which owns them controls any access). It probably shouldn’t be accessed anywhere else, for this use, but you might have something look at the current value to see how many times it has been called. That should probably be protected by the lock as well (to make sure the result is current):