Skip to main content
Ben Nadel at cf.Objective() 2011 (Minneapolis, MN) with: Steven Neiland
Ben Nadel at cf.Objective() 2011 (Minneapolis, MN) with: Steven Neiland ( @sneiland )

Checking CFLock Acquisition Success In Lucee CFML 5.3.8.201

By on
Tags:

Yesterday, in my post about considering the separation of concerns when consuming Amazon SQS queues in Lucee CFML, I created a demo in which I synchronized long-polling requests through the use of an exclusive CFLock tag. For the demo, I had logging in place to trace the workflow of each request; and, as I was putting it together, I noticed that the CFLock tag - at least in Lucee CFML - has an optional result attribute. This result attribute can be used to check whether or not the template was able to successfully access a given lock.

To see this in action, all we have to do is create a CFLock tag that has a sleep() call inside of it. And then, try to run this template with overlapping execution:

<cfscript>

	lock
		result = "lockOutcome"
		name = "testing-lock-acquisition"
		type = "exclusive"
		timeout = 1
		throwOnTimeout = false
		{

		// So we have enough time to create overlapping requests.
		sleep( 5000 );

	}

	// NOTE: I could have used "cflock" instead of "lockOutcome" to reference the
	// following values; but, only if I omitted the "result" attribute.
	echo( "Success: #lockOutcome.succeeded# <br />" );
	echo( "Error: #lockOutcome.errorText#" );

</cfscript>

As you can see, we have a CFLock tag here that will wait 1-second and then skip the lock block if it can't be acquired (hence the throwOnTimeout=false). Then, I'm using the lockOutcome variable to see if the lock was acquired. And, when we run this ColdFusion code in two different browser tabs at the same time, we get this outcome in the first tab:

Success: true
Error:

... and this outcome in second tab:

Success: false
Error: a timeout occurred after 1 second trying to acquire a exclusive lock with name [testing-lock-acquisition].

As you can see, I was able to use the .succeeded property to determine if the CFLock control-flow was entered; or, if it was skipped due to a timeout.

These days, I try to use locks as little as possible, favoring idempotent workflows that lean more heavily on unique database index constraints. But, sometimes I just need a lock. And, it's good to know that I can test that lock outcome in Lucee CFML 5.3.8.201.

Want to use code from this post? Check out the license.

Reader Comments

Post A Comment — I'd Love To Hear From You!

Post a Comment

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel