Script VanWinkle
Script VanWinkle

Reputation: 11

Locking a ColdFusion Application Variable that points to instance of an object

I'm running my applications on CF 9. I created a CFC to concentrate my cookie handling instead of all the tags strewn about. It is simple. It has two attributes (name, value), and has 5 methods (setCookie, deleteCookie, verifyCookie, clearAllCookies, and init).

Since I wanted this method to be available throughout the application, I put this code in the onApplicationStart method of my application.cfc file:

application.oCookie = createObject("com.mycookie").init();

When I need to set a cookie in any code file I just call it like so:

application.oCookie.name="testCookieName";
application.oCookie.value="testCookieValue";
application.oCookie.setCookie();

My question is: Do I need to put a lock on this code each time I do this? If two separate users were to be on pages accessing this code at the same exact instant, can I end up with mixed up cookie values being set?

Upvotes: 1

Views: 93

Answers (1)

Henry
Henry

Reputation: 32915

To make your oCookie thread-safe, it has to be a singleton (with no state) that only acts as a thin layer to the <cfcookie> or the cookie scope.

Therefore you should design your com.mycookie so that it accepts application.oCookie.setCookie(name, value) instead. And make sure you var-scope everything and don't store anything in the variables scope of mycookie.

And I don't think you need to use cflock.

If you haven't already, you may want to checkout WireBox.

Upvotes: 5

Related Questions