Scala有哪些自动资源管理替代方案?

时间:2010-02-05 13:23:18

标签: scala resource-management

我在Web上看到过许多针对Scala的ARM(自动资源管理)示例。虽然大多数看起来很像彼此,但它似乎是一种写作的通道。不过,我 看到了一个非常酷的使用延续的例子。

无论如何,很多代码都有这种或那种类型的缺陷,所以我认为在Stack Overflow上有一个引用是个好主意,我们可以在这里推荐最正确和最合适的版本。

10 个答案:

答案 0 :(得分:73)

Chris Hansen的blog entry 'ARM Blocks in Scala: Revisited' from 3/26/09谈到了Martin Odersky FOSDEM presentation的幻灯片21。下一个块直接从幻灯片21(经许可)获取:

def using[T <: { def close() }]
    (resource: T)
    (block: T => Unit) 
{
  try {
    block(resource)
  } finally {
    if (resource != null) resource.close()
  }
}

- 结束报价 -

然后我们可以这样打电话:

using(new BufferedReader(new FileReader("file"))) { r =>
  var count = 0
  while (r.readLine != null) count += 1
  println(count)
}

这种方法的缺点是什么?这种模式似乎可以解决我需要自动资源管理的95%......

修改添加了代码段


Edit2:扩展设计模式 - 从python with语句和寻址中获取灵感:

  • 在块之前运行的语句
  • 根据托管资源重新抛出异常
  • 使用一个使用语句
  • 处理两个资源
  • 通过提供隐式转换和Managed
  • 来进行特定于资源的处理

这是Scala 2.8。

trait Managed[T] {
  def onEnter(): T
  def onExit(t:Throwable = null): Unit
  def attempt(block: => Unit): Unit = {
    try { block } finally {}
  }
}

def using[T <: Any](managed: Managed[T])(block: T => Unit) {
  val resource = managed.onEnter()
  var exception = false
  try { block(resource) } catch  {
    case t:Throwable => exception = true; managed.onExit(t)
  } finally {
    if (!exception) managed.onExit()
  }
}

def using[T <: Any, U <: Any]
    (managed1: Managed[T], managed2: Managed[U])
    (block: T => U => Unit) {
  using[T](managed1) { r =>
    using[U](managed2) { s => block(r)(s) }
  }
}

class ManagedOS(out:OutputStream) extends Managed[OutputStream] {
  def onEnter(): OutputStream = out
  def onExit(t:Throwable = null): Unit = {
    attempt(out.close())
    if (t != null) throw t
  }
}
class ManagedIS(in:InputStream) extends Managed[InputStream] {
  def onEnter(): InputStream = in
  def onExit(t:Throwable = null): Unit = {
    attempt(in.close())
    if (t != null) throw t
  }
}

implicit def os2managed(out:OutputStream): Managed[OutputStream] = {
  return new ManagedOS(out)
}
implicit def is2managed(in:InputStream): Managed[InputStream] = {
  return new ManagedIS(in)
}

def main(args:Array[String]): Unit = {
  using(new FileInputStream("foo.txt"), new FileOutputStream("bar.txt")) { 
    in => out =>
    Iterator continually { in.read() } takeWhile( _ != -1) foreach { 
      out.write(_) 
    }
  }
}

答案 1 :(得分:60)

丹尼尔,

我刚刚部署了scala-arm库以进行自动资源管理。您可以在此处找到文档:http://wiki.github.com/jsuereth/scala-arm/

此库支持三种使用方式(当前):

1)势在必行/表达:

import resource._
for(input <- managed(new FileInputStream("test.txt")) {
// Code that uses the input as a FileInputStream
}

2)Monadic风格

import resource._
import java.io._
val lines = for { input <- managed(new FileInputStream("test.txt"))
                  val bufferedReader = new BufferedReader(new InputStreamReader(input)) 
                  line <- makeBufferedReaderLineIterator(bufferedReader)
                } yield line.trim()
lines foreach println

3)定界延续式

这是一个“echo”tcp服务器:

import java.io._
import util.continuations._
import resource._
def each_line_from(r : BufferedReader) : String @suspendable =
  shift { k =>
    var line = r.readLine
    while(line != null) {
      k(line)
      line = r.readLine
    }
  }
reset {
  val server = managed(new ServerSocket(8007)) !
  while(true) {
    // This reset is not needed, however the  below denotes a "flow" of execution that can be deferred.
    // One can envision an asynchronous execuction model that would support the exact same semantics as below.
    reset {
      val connection = managed(server.accept) !
      val output = managed(connection.getOutputStream) !
      val input = managed(connection.getInputStream) !
      val writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(output)))
      val reader = new BufferedReader(new InputStreamReader(input))
      writer.println(each_line_from(reader))
      writer.flush()
    }
  }
}

代码使用Resource type-trait,因此它能够适应大多数资源类型。对于使用close或dispose方法的类使用结构类型,它有一个后备。请查看文档,如果您想到要添加的任何便利功能,请告诉我。

答案 2 :(得分:18)

这是使用延续的James Iry解决方案:

// standard using block definition
def using[X <: {def close()}, A](resource : X)(f : X => A) = {
   try {
     f(resource)
   } finally {
     resource.close()
   }
}

// A DC version of 'using' 
def resource[X <: {def close()}, B](res : X) = shift(using[X, B](res))

// some sugar for reset
def withResources[A, C](x : => A @cps[A, C]) = reset{x}

以下是有和没有继续比较的解决方案:

def copyFileCPS = using(new BufferedReader(new FileReader("test.txt"))) {
  reader => {
   using(new BufferedWriter(new FileWriter("test_copy.txt"))) {
      writer => {
        var line = reader.readLine
        var count = 0
        while (line != null) {
          count += 1
          writer.write(line)
          writer.newLine
          line = reader.readLine
        }
        count
      }
    }
  }
}

def copyFileDC = withResources {
  val reader = resource[BufferedReader,Int](new BufferedReader(new FileReader("test.txt")))
  val writer = resource[BufferedWriter,Int](new BufferedWriter(new FileWriter("test_copy.txt")))
  var line = reader.readLine
  var count = 0
  while(line != null) {
    count += 1
    writer write line
    writer.newLine
    line = reader.readLine
  }
  count
}

这是Tiark Rompf提出的改进建议:

trait ContextType[B]
def forceContextType[B]: ContextType[B] = null

// A DC version of 'using'
def resource[X <: {def close()}, B: ContextType](res : X): X @cps[B,B] = shift(using[X, B](res))

// some sugar for reset
def withResources[A](x : => A @cps[A, A]) = reset{x}

// and now use our new lib
def copyFileDC = withResources {
 implicit val _ = forceContextType[Int]
 val reader = resource(new BufferedReader(new FileReader("test.txt")))
 val writer = resource(new BufferedWriter(new FileWriter("test_copy.txt")))
 var line = reader.readLine
 var count = 0
 while(line != null) {
   count += 1
   writer write line
   writer.newLine
   line = reader.readLine
 }
 count
}

答案 3 :(得分:7)

我看到在Scala中执行ARM的渐进式4步演变:

  1. No ARM:Dirt
  2. 只有闭包:更好,但多个嵌套块
  3. Continuation Monad:用于平整嵌套,但在2个块中不自然分离
  4. 直接风格延续:Nirava,啊哈!这也是最类型安全的替代方法:withResource块外部的资源将是类型错误。

答案 4 :(得分:6)

更好的文件包含轻量级(10行代码)ARM。请参阅:https://github.com/pathikrit/better-files#lightweight-arm

some data here
0,0,9;
1,0,10;
1,1,11;

如果您不想要整个库,请执行以下操作:

import better.files._
for {
  in <- inputStream.autoClosed
  out <- outputStream.autoClosed
} in.pipeTo(out)
// The input and output streams are auto-closed once out of scope

答案 5 :(得分:2)

目前Scala 2.13终于支持:try with resources通过使用Using :),示例:

val lines: Try[Seq[String]] =
  Using(new BufferedReader(new FileReader("file.txt"))) { reader =>
    Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
  }

或使用Using.resource避免使用Try

val lines: Seq[String] =
  Using.resource(new BufferedReader(new FileReader("file.txt"))) { reader =>
    Iterator.unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
  }

您可以从Using文档中找到更多示例。

  

用于执行自动资源管理的实用程序。它可以用于执行使用资源的操作,然后按照创建资源的相反顺序释放资源。

答案 6 :(得分:1)

如何使用Type类

trait GenericDisposable[-T] {
   def dispose(v:T):Unit
}
...

def using[T,U](r:T)(block:T => U)(implicit disp:GenericDisposable[T]):U = try {
   block(r)
} finally { 
   Option(r).foreach { r => disp.dispose(r) } 
}

答案 7 :(得分:1)

另一种选择是Choppy的Lazy TryClose monad。它与数据库连接相当不错:

pip uninstall

还有溪流:

val ds = new JdbcDataSource()
val output = for {
  conn  <- TryClose(ds.getConnection())
  ps    <- TryClose(conn.prepareStatement("select * from MyTable"))
  rs    <- TryClose.wrap(ps.executeQuery())
} yield wrap(extractResult(rs))

// Note that Nothing will actually be done until 'resolve' is called
output.resolve match {
    case Success(result) => // Do something
    case Failure(e) =>      // Handle Stuff
}

此处有更多信息:https://github.com/choppythelumberjack/tryclose

答案 8 :(得分:0)

这里是@chengpohi的答案,已对其进行了修改,以便它可以与Scala 2.8+一起使用,而不仅仅是Scala 2.13(是的,它也适用于Scala 2.13):

def unfold[A, S](start: S)(op: S => Option[(A, S)]): List[A] =
  Iterator
    .iterate(op(start))(_.flatMap{ case (_, s) => op(s) })
    .map(_.map(_._1))
    .takeWhile(_.isDefined)
    .flatten
    .toList

def using[A <: AutoCloseable, B](resource: A)
                                (block: A => B): B =
  try block(resource) finally resource.close()

val lines: Seq[String] =
  using(new BufferedReader(new FileReader("file.txt"))) { reader =>
    unfold(())(_ => Option(reader.readLine()).map(_ -> ())).toList
  }

答案 9 :(得分:0)

虽然 Using 可以,但我更喜欢资源组合的 monadic 风格。 Twitter Util 的 Managed 非常好,除了它的依赖项和不太完善的 API。

为此,我为 Scala 2.12、2.13 和 3.0.0 发布了 https://github.com/dvgica/managerial。主要基于 Twitter Util Managed 代码,没有依赖项,一些 API 改进受到了 cat-effect Resource 的启发。

简单的例子:

import ca.dvgi.managerial._
val fileContents = Managed.from(scala.io.Source.fromFile("file.txt")).use(_.mkString)

但图书馆的真正实力是composing resources via for comprehensions

告诉我你的想法!

相关问题