Can anyone help me build a DSL for holding resources? I want to use it similar to Java's synchronized
, so that if a resource (java: an object monitor) is already acquired it won't get acquired again! (For the followin开发者_如何学Pythong example resources are assumed to be of type Int
)
object Holding {
def main(args : Array[String]) : Unit = {
HoldResource(1,2,3) {
// holding resource 1,2,3
println("!")
HoldResource(3) {
// still holding resource 1,2,3 (but not acquiring resource 3 again!!!)
println("*")
}
println("!!")
HoldResource(4,5) {
// holding resource 1,2,3,4,5
println("#")
}
println("!!!")
}
// all resources are freed
}
}
Until now my ROUGH approach looks like this (that means I know about the try { ... } finally { ... }
resource-pattern.) :
object HoldResource {
class Context(val resources: Seq[Int]) {
def apply[A](f: => A): A = {
try { f } finally {
// free resources
}
}
}
def apply[A](resources: Int*): Context = {
// lock/acquire resources
new Context(resources)
}
}
Thanks a lot!
It looks like you're after Software Transactional Memory.
Try these articles to get you started:
- STM in Scala
- Improving STM with MVCC
There's also some useful material on resource management:
- Article: ARM blocks in Scala
- Github: scala-arm
精彩评论