43Using CFX Tags Safely: Locking and Thread Safety
Either line of code, used immediately before the CFX tag, will guard against any potential problems
if the CFX tag tries to add nested structures to an existing variable that is not itself a structure.
Whew, that was close!
Using CFX Tags Safely: Locking and Thread Safety
Because the ColdFusion server responds to page requests in a multithreaded fashion (meaning that
it can process more than one page request at the same time), it is possible that two instances of a CFX
tag may execute on the same server at the same time. If the CFX tag is not thread-safe in terms of
how it deals with memory or how it works logically, problems might arise unless you take steps to
avoid them. Like other concurrency issues, such problems are likely to show up only under load,
making it appear that the tag (or ColdFusion itself) does not scale well, when in fact the problem
could be avoided by making sure the tag does not execute in more than one page request at once.
Understanding Thread Safety
A full discussion of what it means for a compiled program to be thread-safe is well beyond the scope
of what can be explained in this chapter. For purposes of this discussion, it will have to suffice that
thread-safe basically means that the tag has been coded in such a way that it can run in several threads
at the same time without any possibility of the various threads being able to create, change, edit—
or, in some instances, merely access-a shared resource (where shared resource means any shared vari-
able, memory, file, or the like).
Generally speaking, a CFX tag is probably thread-safe if it does not use any global variables (that is,
if none of the variables are declared outside of the
processRequest() function in Java or the
ProcessTagRequest() function in C++) and also does not access any external or third-party APIs
that themselves are not thread-safe.
NOTE
If you’re not familiar with what a thread is, don’t worry about it too much right now. In the context of ColdFusion, a thread is basically
the same thing conceptually as a page request from a user (because each simultaneous page request is processed by a different
worker thread within the server).
Locking CFX Tags with <cflock>
You can still use CFX tags even if you know they aren’t thread-safe. Just wrap the <cflock> tag around
every use of the tag, using
type=”Exclusive” and a name attribute equal to the name of the CFX tag
(or some other name, as long as it is always the same for every single use of the tag). For instance, if
you knew (or suspected) that the
<CFX_ComputeStatistics> tag was not thread-safe, you would use
code similar to the following:
<cflock type=”Exclusive”
name=”CFX_ComputeStatistics”
timeout=”10”>
<!--- Compute statistics for the ratings of each film --->
<CFX_ComputeStatistics query=”GetFilms”
column=”RatingID”
variable=”FilmsStats”>
</cflock>
Kommentare zu diesen Handbüchern