Skip to main content
Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.

Checking CFLock Acquisition Success In Lucee CFML 5.3.8.201

By Ben Nadel on
Tags: ColdFusion

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.



Reader Comments

What has two thumbs and hopes you leave a comment? This Guy! (Ben Nadel).

Post A Comment

You — Get Out Of My Dreams, Get Into My Blog
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.