Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java try-with-resource not working with scala

In Scala application, am trying to read lines from a file using java nio try-with-resource construct.

Scala version 2.11.8
Java version 1.8

try(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){
    stream.forEach(System.out::println); // will do business process here
}catch (IOException e) {
    e.printStackTrace(); // will handle failure case here
}  

But the compiler throws error like
◾not found: value stream
◾A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.

Not sure what is the problem. Am new to using Java NIO, so any help is much appreciated.

like image 398
Rajkumar S Avatar asked Oct 05 '16 05:10

Rajkumar S


People also ask

Does Scala have try with resources?

Overview. In Java, we can use the try-with-resources statement to automatically close all resources that we need in our code. This statement works with every class that implements the AutoCloseable interface. Unfortunately, such a feature does not exist in Scala.

What is AutoCloseable interface in Java?

public interface AutoCloseable. An object that may hold resources (such as file or socket handles) until it is closed. The close() method of an AutoCloseable object is called automatically when exiting a try -with-resources block for which the object has been declared in the resource specification header.


2 Answers

If your are on Scala 2.13 then you should use the Using object:

import scala.util.Using
val a: Try[Int] = Using(new FileInputStream("/tmp/someFile")) { fileInputStream =>
  // Do what you need in fith you fileInputStream here.
}

It takes two functions. The first one is a function that can create or provide the closable resource, and the second function is the one that takes the closable resource as a parameter, and can use it for something. Using will then in simple terms do the following for you:

  1. Call the first function to create the closable resource.
  2. Call the second function, and provide the resource as a parameter.
  3. Hold on to the returned value of the second function.
  4. Call close on the resource.
  5. Return the value (or exception) it got from the second function wrapped in a Try.

Using can be used on many other things than Classes that implements AutoCloseable, you just have to provide an implicit value, telling Using how to close your specific resource.

In older versions of scala, there is no directly support for javas try-with-resources construct, but your can pretty easy build your own support, by applying the loan pattern. The following is a simple but not optimal example, that is easy to understand. A more correct solution is given later in this answer:

import java.lang.AutoCloseable

def autoClose[A <: AutoCloseable,B](
        closeable: A)(fun: (A) ⇒ B): B = {
    try {
        fun(closeable)
    } finally {
        closeable.close()
    }
}

This defines a reusable method, that works pretty much like a try-with-resource construct in java. It works by taken two parameter. First is takes the a subclass of Autoclosable instance, and second it takes a function that takes the same Autoclosable type as a paremeter. The return type of the function parameter, is used as return type of the method. The method then executes the function inside a try, and close the autocloseble in its finally block.

You can use it like this (here used to get the result of findAny() on the stream.

val result: Optional[String] = autoClose(Files.lines(Paths.get("somefile.txt"))) { stream ⇒
    stream.findAny()
}

In case your want to do catch exceptions, you have 2 choices.

  1. Add a try/catch block around the stream.findAny() call.

  2. Or add a catch block to the try block in the autoClose method. Note that this should only be done, if the logic inside the catch block is usable from all places where autoClose is called.

Note that as Vitalii Vitrenko point out, this method will swallow the exception from the close method, if both the function supplied by the client, and the close method on the AutoCloseable throws an exception. Javas try-with-resources handles this, and we can make autoClose do so to, by making it a bit more complex:

  def autoClose[A <: AutoCloseable,B](
      closeable: A)(fun: (A) ⇒ B): B = {

    var t: Throwable = null
    try {
      fun(closeable)
    } catch {
      case funT: Throwable ⇒
        t = funT
        throw t
    } finally {
      if (t != null) {
        try {
          closeable.close()
        } catch {
          case closeT: Throwable ⇒
            t.addSuppressed(closeT)
            throw t
        }
      } else {
        closeable.close()
      }
    }
  }

This works by storing the potentially exception the client function throws, and adding the potential exception of the close method to it as a supressed exception. This is pretty close to how oracle explains that try-with-resource is actually doing it: http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html

However this is Scala, and a lot of people will prefer to program in a more functional way. In a more functional way, the method should return a Try, instead of throwing an exception. This avoids a side effect of throwing an exception, and makes it clear to the client that the response may be a failure that should be handled (as pointed out in the answer by Stas). In a functional implementation, we would also like to avoid having a var, so a naive attempt could be:

  // Warning this implementation is not 100% safe, see below
  def autoCloseTry[A <: AutoCloseable,B](
      closeable: A)(fun: (A) ⇒ B): Try[B] = {

    Try(fun(closeable)).transform(
      result ⇒ {
        closeable.close()
        Success(result)
      },
      funT ⇒ {
        Try(closeable.close()).transform(
          _ ⇒ Failure(funT),
          closeT ⇒ {
            funT.addSuppressed(closeT)
            Failure(funT)
          }
        )
      }
    )
  }

This could them be called like this:

    val myTry = autoCloseTry(closeable) { resource ⇒
      //doSomethingWithTheResource
      33
    }
    myTry match {
      case Success(result) ⇒ doSomethingWithTheResult(result)
      case Failure(t) ⇒ handleMyExceptions(t)
    }

Or you could just call .get on myTry to make it return the result, or throw the exception.

However as Kolmar points out in a comment, this implementation is flawed, due to how the return statement works in scala. Consider the following:

  class MyClass extends AutoCloseable {
    override def close(): Unit = println("Closing!")
  }

  def foo: Try[Int] = {
     autoCloseTry(new MyClass) { _ => return Success(0) }
  }

  println(foo)

We would expect this to print Closing!, but it will not. The problem here is the explicit return statement inside the function body. It makes the method skip the logic in the autoCloseTry method, and thereby just returns Success(0), without closing the resource.

To fix that problem, we can create a mix of the 2 solutions, one that has the functional API of returning a Try, but uses the classic implementation based on try/finally blocks:

    def autoCloseTry[A <: AutoCloseable,B](
        closeable: A)(fun: (A) ⇒ B): Try[B] = {

      var t: Throwable = null
      try {
        Success(fun(closeable))
      } catch {
        case funT: Throwable ⇒
          t = funT
          Failure(t)
      } finally {
        if (t != null) {
          try {
            closeable.close()
          } catch {
            case closeT: Throwable ⇒
              t.addSuppressed(closeT)
              Failure(t)
          }
        } else {
          closeable.close()
        }
      }
    }

This should fix the problem, and can be used just like the first attempt. However it shows that this a bit error prone, and the faulty implementation has been in this answer as the recommended version for quite some time. So unless you trying to avoid having to many libraries, you should properly consider using this functionality from a library. I think that there is already one other answer pointing to one, but my guess is that there is multiply libraries, that solves this problem in different ways.

like image 113
Anders Kreinøe Avatar answered Oct 16 '22 14:10

Anders Kreinøe


Alternatively, you can use Choppy's (Disclaimer: I am the author) TryClose monad do this in a for-comprehension in a composeable manner similar to Scala's Try.

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))

Here's how you would do it with your stream:

val output = for {
  stream  <- TryClose(Files.lines(Paths.get("somefile.txt")))
} yield wrap(stream.findAny())

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

like image 3
Choppy The Lumberjack Avatar answered Oct 16 '22 15:10

Choppy The Lumberjack