DynamicVariable
is an implementation of the loan and dynamic scope patterns. Use-case of DynamicVariable
is pretty much similar to ThreadLocal
in Java (as a matter of fact, DynamicVariable
uses InheritableThreadLocal
behind the scenes) - it's used, when you need to do a computation within an enclosed scope, where every thread has it's own copy of the variable's value:
dynamicVariable.withValue(value){ valueInContext =>
// value used in the context
}
Given that DynamicVariable
uses an inheritable ThreadLocal
, value of the variable is passed to the threads spawned in the context:
dynamicVariable.withValue(value){ valueInContext =>
spawn{
// value is passed to the spawned thread
}
}
DynamicVariable
(and ThreadLocal
) is used in Scalatra for the same reason it's used in many other frameworks (Lift, Spring, Struts, etc.) - it's a non-intrusive way to store and pass around context(thread)-specific information.
Making HttpServletResponse
and HttpServletRequest
dynamic variables (and, thus, binding to a specific thread that processes request) is just the easiest way to obtain them anywhere in the code (not passing through method arguments or anyhow else explicitly).