liveBook · Manning

Resource leak

As explained in Functional Programming in Scala, Second Edition

A resource leak is failure to release an acquired resource, such as an open file handle, after it is no longer needed.

A resource leak occurs when an acquired resource remains unreleased after it is no longer needed. An open file handle can survive an exception, consuming one of the operating system’s limited file slots. section 15.1

Resource-safe code should:

  • Close file handles as soon as they are no longer needed, including after exceptional termination. section 15.1
  • Avoid reading from resources after they have been closed. section 15.1
  • Apply the same discipline to network sockets and database connections. section 15.1

Exception-safe file processing

An imperative line-counting program opens a file, processes its iterator, and closes the source in a finally block. Omitting that finally block, or closing the file afterward, can leak the handle when processing raises an exception. section 15.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains normal and exceptional cleanup, then stops short of presenting a compiler-enforced resource-safety implementation.
Examples
Uses an imperative Scala file counter whose finally block closes the source after incremental iteration.
What it assumes
Assumes familiarity with files, iterators, exceptions, and finally blocks while defining scarce resources through file handles.
What you can do after
Diagnose leaks by identifying acquired resources whose cleanup is omitted or bypassed by exceptions.
How it connects
Connects resource leaks with file handles, exceptions, incremental I/O, network sockets, database connections, and resource safety.

Also explained in

Compare how 3 books explain resource leak →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.