Thread-safe sequential number generator in ColdFusion?
If I have a Generator.cfc with methods:
numeric function next()
{
return variables.num++; // Is ++ an atomic operation??
}
And:
application.generator = new generator();
If every request calls application.generat开发者_开发问答or.next(), will this generator ever generate the same number twice on heavy load? In another word... is this thread-safe? If not, where should the lock be?
You could also look into the Java 5 class Atomic Integer
The ColdFusion code you need is something like this (I haven't tested it):
<cfset i = createObject("java", "java.util.concurrent.atomic.AtomicInteger").init(startValue) />
<cfset newValue = i.incrementAndGet() />
You can make it atomic by wrapping the increment in a lock. Since ++
requires three operations (fetch, add, store) I don't think it's atomic on its own on any platform.
Yep, as Donnie pointed out CFLOCK is your friend here.
精彩评论