What is DynamicVariable ?
DynamicVariable is used to bind values dynamically for the scope specified in parameter-less closure. They are like Java's ThreadLocal. They are global variable storing separate value for each thread.
When to create dynamic variables ?
When different threads have different context to work on. So instead of passing context from functions to functions, we store them in thread local variables aka dynamic variables.
When object shared is not thread-safe, so it's better to assign one to each thread.
Dynamic variables holds the new values using withValue method and this value is applicable only to this scope, no matter how many nested child threads you have, each thread will be able to access this value.
For example:
DynamicVariable is using InheritableThreadLocal internally, so be careful while using DynamicVariable where value is stateful or following some strict life-cycle, for example: database connection. It should be used where context is thread-safe, immutable.
Second argument of function withValue can have child thread and can still use value in that closure.
See in following example:
DynamicVariable is used to bind values dynamically for the scope specified in parameter-less closure. They are like Java's ThreadLocal. They are global variable storing separate value for each thread.
When to create dynamic variables ?
When different threads have different context to work on. So instead of passing context from functions to functions, we store them in thread local variables aka dynamic variables.
When object shared is not thread-safe, so it's better to assign one to each thread.
Dynamic variables holds the new values using withValue method and this value is applicable only to this scope, no matter how many nested child threads you have, each thread will be able to access this value.
For example:
val dyn = new DynamicVariable[Int](0)
new Thread(new Runnable() {
def run() {
dyn.withValue(10) { doSomething }
}
}, "thread-1").start()
new Thread(new Runnable() {
def run() {
dyn.withValue(20) { doSomething }
}
}, "thread-2").start()
def doSomething() {
println {
Thread.currentThread().getName() +
" " + dyn.value
}
}
Output:thread-1 10 thread-2 20
DynamicVariable is using InheritableThreadLocal internally, so be careful while using DynamicVariable where value is stateful or following some strict life-cycle, for example: database connection. It should be used where context is thread-safe, immutable.
Second argument of function withValue can have child thread and can still use value in that closure.
See in following example:
val dyn = new DynamicVariable[Int](0)
dyn.withValue(10) {
new Thread(new Runnable() {
def run() {
{ doSomething }
}
}, "thread-1").start()
}
def doSomething {
println {
Thread.currentThread().getName() +
" " + dyn.value
}
}
Output:
thread-1 10
gotcha
ReplyDeletetnx!
ReplyDelete