开发者

DSL for holding resources

开发者 https://www.devze.com 2023-02-05 02:26 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号