Skip to main content
Version: 2.x

Introduction to Resource Management in ZIO

When we are writing a long-lived application, resource management is very important. Proper resource management is vital to any large-scale application. We need to make sure that our application is resource-safe, and it doesn't leak any resource.

Leaking socket connections, database connections or file descriptors is not acceptable in a web application. ZIO provides several constructs that guarantee resources are released.

To write a resource-safe application, we need to make sure whenever we are opening a resource, we have a mechanism to close that resource whether we use that resource completely or not, for example, an exception occurred during resource usage.

Try / Finally​

Before we dive into the ZIO solution, it's better to review the try / finally which is the standard approach in the Scala language to manage resources.

Scala has a try / finally construct which helps us to make sure we don't leak resources because no matter what happens in the try, the finally block will be executed. So we can open files in the try block, and then we can close them in the finally block, and that gives us the guarantee that we will not leak resources.

Assume we want to read a file and return the number of its lines:

def lines(file: String): Task[Long] = ZIO.attempt {
def countLines(br: BufferedReader): Long = br.lines().count()
val bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(file)),
2048
)
val count = countLines(bufferedReader)
bufferedReader.close()
count
}

What happens if after opening the file and before closing the file, an exception occurs? So, the bufferedReader.close() line, doesn't have a chance to close the resource. This creates a resource leakage. The Scala language has the try...finally construct, which helps us prevent these situations.

Let's rewrite the above example with try..finally:

def lines(file: String): Task[Long] = ZIO.attempt {
def countLines(br: BufferedReader): Long = br.lines().count()
val bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(file)),
2048
)
try countLines(bufferedReader)
finally bufferedReader.close()
}

Now, if countLines throws an exception, the finally block still closes the reader.

try / finally solves simple problems, but it has some drawbacks:

  1. It's not composable; We can't compose multiple resources together.

  2. When we have multiple resources, we end up with messy and ugly code, hard to reason about, and refactoring.

  3. We don't have any control over the order of resource clean-up

  4. It only helps us to handle resources sequentially. It can't compose multiple resources, concurrently.

  5. It doesn't support asynchronous workflows.

  6. It's a manual way of resource management, not automatic. To have a resource-safe application we need to manually check that all resources are managed correctly. This way of resource management is error-prone in case of forgetting to manage resources, correctly.

ZIO Solution​

ZIO's resource management features work across synchronous, asynchronous, concurrent, and other effect types, and provide strong guarantees even in the presence of failure, interruption, or defects in the application.

ZIO has two major mechanisms to manage resources.

Acquire Release​

ZIO generalizes the try / finally pattern as ZIO.acquireReleaseWith(acquire)(release)(use). The scoped forms, ZIO.acquireRelease and ZIO#withFinalizer, are covered under Scope.

Every acquire release requires three actions:

  1. Acquiring Resourceβ€” An effect describing the acquisition of resource. For example, opening a file.
  2. Using Resourceβ€” An effect describing the actual process to produce a result. For example, counting the number of lines in a file.
  3. Releasing Resourceβ€” An effect describing the final step of releasing or cleaning up the resource. For example, closing a file.
def use(resource: Resource): Task[Any] = ZIO.attempt(???)
def release(resource: Resource): UIO[Unit] = ZIO.succeed(???)
def acquire: Task[Resource] = ZIO.attempt(???)

val result: Task[Any] = ZIO.acquireReleaseWith(acquire)(release)(use)

acquireReleaseWith runs acquire and release uninterruptibly, and runs release whenever acquire succeeded, whether use succeeds, fails or is interrupted. When acquire fails, there is nothing to release, and release does not run.

Let's try a real example. We are going to write a function that counts the lines of a file. As we are working with a file resource, we separate our logic into three parts. First, we create a BufferedReader. Second, we count the lines with that BufferedReader, and at the end we close it:

def lines(file: String): Task[Long] = {
def countLines(reader: BufferedReader): Task[Long] = ZIO.attempt(reader.lines().count())
def releaseReader(reader: BufferedReader): UIO[Unit] = ZIO.succeed(reader.close())
def acquireReader(file: String): Task[BufferedReader] = ZIO.attempt(new BufferedReader(new FileReader(file), 2048))

ZIO.acquireReleaseWith(acquireReader(file))(releaseReader)(countLines)
}

Let's write another function which copies a file from a source to a destination file. We can do that by nesting two acquire releases one for the FileInputStream and the other for FileOutputStream:

def is(file: String): Task[FileInputStream] = ZIO.attempt(???)
def os(file: String): Task[FileOutputStream] = ZIO.attempt(???)

def close(resource: Closeable): UIO[Unit] = ZIO.succeed(???)
def copy(from: FileInputStream, to: FileOutputStream): Task[Unit] = ???

def transfer(src: String, dst: String): ZIO[Any, Throwable, Unit] = {
ZIO.acquireReleaseWith(is(src))(close) { in =>
ZIO.acquireReleaseWith(os(dst))(close) { out =>
copy(in, out)
}
}
}

As there isn't any dependency between our two resources (is and os), we might want to acquire them together, for example with is(src).zipPar(os(dst)) as the acquire of a single acquireReleaseWith. That does not work well: release runs only when the whole acquire succeeds, so when one of the two acquisitions fails, the stream that the other one opened is never closed. Each resource needs its own release, which brings us back to nesting.

While using acquire release is a nice and simple way of managing resources, but there are some cases where an acquire release is not the best choice:

  1. Acquire release is not composableβ€” When we have multiple resources, composing them with an acquire release is not straightforward.

  2. Messy nested acquire releases β€” In the case of multiple resources, nested acquire releases remind us of callback hell awkwardness. The acquire release is designed with nested resource acquisition. In the case of multiple resources, we encounter inefficient nested acquire release calls, and it causes refactoring a complicated process.

Using acquire releases is simple and straightforward, but in the case of multiple resources, it does not scale well. This is where we need another abstraction to cover these issues.

Scope​

A Scope collects finalizers and runs them when it is closed. ZIO.acquireRelease acquires a resource and adds its release to the Scope in the environment, so the effect it returns has type ZIO[R with Scope, E, A].

To create a scoped resource, we provide the acquire and release actions of that resource to the acquireRelease constructor:

val scoped = ZIO.acquireRelease(acquire)(release)

We use a scoped resource inside ZIO.scoped { … }, which closes the scope, and so releases the resource, when the block completes. The resource is meant to be used only inside that block.

Let's try to rewrite a transfer example with Scope:

def transfer(from: String, to: String): ZIO[Any, Throwable, Unit] = {
val resource = for {
from <- ZIO.acquireRelease(is(from))(close)
to <- ZIO.acquireRelease(os(to))(close)
} yield (from, to)

ZIO.scoped {
resource.flatMap { case (in, out) =>
copy(in, out)
}
}
}

Because each resource has its own release, we can also acquire the two files in parallel. When one acquisition fails, the file that the other one opened is still closed when the scope closes:

def transfer(from: String, to: String): ZIO[Any, Throwable, Unit] =
ZIO.scoped {
ZIO
.acquireRelease(is(from))(close)
.zipPar(ZIO.acquireRelease(os(to))(close))
.flatMap { case (in, out) => copy(in, out) }
}

Next Steps​

ZIO Chat

πŸŽ‰ Hey there, ZIO aficionado! πŸŽ‰ Step into the ZIO wonderland with me as your guide. Whether you're a functional fanatic or just dipping your toes into the ZIO ecosystem, I'm here to make your journey smooth. Got ZIO questions? I've got answers! Let's navigate the ZIO universe together and unlock its infinite possibilities!