用于保存资源的 DSL
谁能帮我构建一个 DSL 来保存资源?我想像Java的synchronized
一样使用它,这样如果一个资源(java:对象监视器)已经被获取,它就不会再次被获取! (对于以下示例,资源假定为 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
}
}
到目前为止,我的粗略方法看起来像这样(这意味着我知道 try { ... } finally { ... }
资源模式。):
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)
}
}
非常感谢!
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 following 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您正在寻找软件事务内存。
尝试这些文章来帮助您入门:
还有一些有关资源管理的有用材料:
It looks like you're after Software Transactional Memory.
Try these articles to get you started:
There's also some useful material on resource management: