tags:

views:

153

answers:

3

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.generator.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?

+4  A: 

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.

Donnie
I think you're right about `++` but there are atomic ways of incrementing without locks on some platforms. `Interlocked.Increment` on .NET, for example. If Java has an equivalent, it might be possible to call that directly and avoid the performance hit of locking.
Joel Mueller
I see I didn't read far enough before commenting, Java does have such a construct, as Bob points out.
Joel Mueller
+2  A: 

Yep, as Donnie pointed out CFLOCK is your friend here.

Cody Caughlan
+3  A: 

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() />
Bob Albright
nice, I like this!
Henry