问题描述
当我阅读scalatra的源代码时,我发现有一些代码如下:
When I read the source of scalatra, I found there are some code like:
protected val _response = new DynamicVariable[HttpServletResponse](null)
protected val _request = new DynamicVariable[HttpServletRequest](null)
有一个有趣的类,名为DynamicVariable
.我看过这门课的文档,但我不知道我们什么时候以及为什么应该使用它?它有一个通常使用的 withValue()
.
There is an interesting class named DynamicVariable
. I've looked at the doc of this class, but I don't know when and why we should use it? It has a withValue()
which is usually be used.
如果我们不使用它,那么我们应该使用什么代码来解决它解决的问题?
If we don't use it, then what code we should use instead, to solve the problem it solved?
(我是 Scala 的新手,如果你能提供一些代码,那就太好了)
(I'm new to scala, if you can provide some code, that will be great)
推荐答案
DynamicVariable
是贷款和动态范围模式的实现.DynamicVariable
的用例与 Java 中的 ThreadLocal
非常相似(事实上,DynamicVariable
使用 InheritableThreadLocal
> 在幕后) - 当您需要在封闭范围内进行计算时使用它,其中每个线程都有自己的变量值副本:
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
}
鉴于 DynamicVariable
使用可继承的 ThreadLocal
,变量的值被传递给上下文中产生的线程:
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
(和 ThreadLocal
)在 Scalatra 中使用的原因与在许多其他框架(Lift、Spring、Struts 等)中使用的原因相同 - 它是非- 存储和传递上下文(线程)特定信息的侵入式方式.
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.
制作 HttpServletResponse
和 HttpServletRequest
动态变量(并因此绑定到处理请求的特定线程)只是在代码中的任何位置获取它们的最简单方法(不传递方法参数或以其他任何方式显式传递).
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).
这篇关于我们什么时候应该使用 scala.util.DynamicVariable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!