Question

I'm looking at the scala-arm library, prompted by this answer, and it looks great for managing resources in most contexts.

There's one context, though, that it doesn't, on first glance, appear to handle: that of "handing off" a resource to another resource. This comes up frequently when working with I/O:

for (fin <- managed(new FileInputStream(file));
     // almost what we want, except see below
     gzip <- managed(new GZIPInputStream(fin));
     src <- managed(Source.fromInputStream(gzip))) {
  /* some fancy code */
}

Now, the problem is this: If gzip is successfully created, then it is responsible for closing fin, and fin should not be closed (update: this isn't quite right - double-close is fine; see accepted answer). The alternative, though:

for (src <- managed(Source.fromInputStream(
              new GZIPInputStream(new FileInputStream(file))))) {
  /* some fancy code */
}

is not quite correct - if there is an (admittedly unlikely) error in the GZIPInputStream constructor, the FileInputStream is not closed. Ditto for fromInputStream.

Does scala-arm (or some other package) provide a facility for handling this cleanup safely that I haven't found yet?

Was it helpful?

Solution

Did a few more minutes of looking, and found that it really doesn't matter. java.io.Closeable stipulates that close()ing an already-closed resource is a no-op. So it's safe to wrap everything in managed and let it double-close. The first code example, therefore, is correct.

OTHER TIPS

The best approach to me is to use the notion of iteratee, enumerator and enumeratee that has its fundation in the functional world.

What you might be interested in is the Scalaz library that have a very good implementation.

In some words those concepts are used in order to have both the iterator on the source knowing when the consummator had ended consumming but also the other way around. Having the cons knowing the source has nothing to provide.

EDIT

Here is a very clear post on what iteratee are for. See the motivation parameter that talks about your problem... closing resources whenever what went well or wrong, but at the right time

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top