Scala finally block closing/flushing resource

后端 未结 3 649
清歌不尽
清歌不尽 2020-12-09 03:23

Is there a better way to ensure resources are properly released - a better way to write the following code ?

        val out: Option[FileOutputStream] = try         


        
相关标签:
3条回答
  • 2020-12-09 03:57

    Something like that is a good idea, but I'd make it a method:

    def cleanly[A,B](resource: => A)(cleanup: A => Unit)(code: A => B): Option[B] = {
      try {
        val r = resource
        try { Some(code(r)) }
        finally { cleanup(r) }
      } catch {
        case e: Exception => None
      }
    }
    

    (note that we only catch once; if you really want a message printed in one case and not the other, then you do have to catch both like you did). (Also note that I only catch exceptions; catching Error also is usually unwise, since it's almost impossible to recover from.) The method is used like so:

    cleanly(new FileOutputStream(path))(_.close){ fos =>
      Iterator.continually(in.read).takeWhile(_ != -1).foreach(fos.write)
    }
    

    Since it returns a value, you'll get a Some(()) if it succeeded here (which you can ignore).


    Edit: to make it more general, I'd really have it return an Either instead, so you get the exception. Like so:

    def cleanly[A,B](resource: => A)(cleanup: A => Unit)(code: A => B): Either[Exception,B] = {
      try {
        val r = resource
        try { Right(code(r)) } finally { cleanup(r) }
      }
      catch { case e: Exception => Left(e) }
    }
    

    Now if you get a Right, all went okay. If you get a Left, you can pick out your exception. If you don't care about the exception, you can use .right.toOption to map it into an option, or just use .right.map or whatever to operate on the correct result only if it is there (just like with Option). (Pattern matching is a useful way to deal with Eithers.)

    0 讨论(0)
  • 2020-12-09 04:14

    Alternatively you can do this with Choppy's Lazy TryClose monad.

    val output = for {
      fin   <- TryClose(in)
      fout  <- TryClose.wrapWithCloser(new FileOutputStream(path))(out => {out.flush(); out.close();})
    } yield wrap(Iterator.continually(fin.read).takeWhile(-1 != _).foreach(fout.get.write))
    
    // Then execute it like this:
    output.resolve
    

    More info here: https://github.com/choppythelumberjack/tryclose

    (just be sure to import tryclose._ and tryclose.JavaImplicits._)

    0 讨论(0)
  • 2020-12-09 04:15

    Have a look at Scala-ARM

    This project aims to be the Scala Incubator project for Automatic-Resource-Management in the scala library ...

    ... The Scala ARM library allows users to ensure opening closing of resources within blocks of code using the "managed" method. The "managed" method essentially takes an argument of "anything that has a close or dispose method" and constructs a new ManagedResource object.

    0 讨论(0)
提交回复
热议问题