Threads, Locks, and Shared Scope - JessicaOPRD/docs GitHub Wiki
This is a topic you can remain blissfully unaware of until you encounter a problem with concurrent requests and race conditions, yielding supremely bizarre string concatenation, number addition, JSON serialization, etc. Look closely, and you may start to see that seemingly separate requests have, like Frankenstein, come together to form an unexpected, unnatural result. It might be fun to explore if not for how often it's ruining someone's page request.
Shared libraries
I began encountering this issue with "some" regularity after an application's functional/utility libraries were added to its shared in-memory scope. I struggled to find much information about the acceptability of this technique and what kinds of traps might exist. In ColdFusion, the docs assume you are storing variables like integers or strings on this scope. There is some chatter on Stack Overflow. Some guidelines to keep in mind:
-
Stay stateless — Take a functional or at least stateless approach to these methods.
-
Use local scope only — This is the least clear constraint. In ColdFusion, you can declare a "local" variable using either the
var
keyword or the explicitlocal
scope (there are subtle differences between the two —local
is safest but less natural between languages). If you omitvar
, as I have sometimes done in afor
loop declaration, you are actually defining the variable on a completely separatevariables
scope that is shared/not thread-safe. This helps to explain odd accumulation/traversal results.
I suspect there are a couple of other guidelines, involving read/write operations that likely require locks, when to expect bottlenecks out of your locks, and when to spin up your own thread.
"Write-once" variables
These are variables set on the first user's visit, and subsequent users read the results. Often this is a caching operation. In the context of reading/writing to shared scope (outside of safe functions since as Application.cfc
's onApplicationStart
), a lock is required. In particular, a "double-checked lock" may be necessary.
- Performing A Double-Check Lock Around "Run Once" Code In ColdFusion
- Race Conditions: Double Locking
- Another example of double locking
Threading
Scope is limited in threads (do not expect access to shared scope). More information here.
Here is a very good cheat sheet of all scopes in ColdFusion.