Posts Tagged ‘dynamic extent’

Dynamic Extent in Java

Posted Jun 28 2013 by in Java with 1 Comment

In my work, I tend to borrow heavily from the Lisp tradition, even when writing in Java. One of my go to techniques from the ‘Lisp world’ is using Runnable‘s in API’s to explicitly enforce dynamic extent. Without getting too heavily into the Lisp-specific terminology, dynamic extent is what you need to write code for the following kinds of scenarios:

  • ‘Ensure that an opened file is closed, after it’s been used’
  • ‘Ensure that this lock is released at the end of this critical section’.

These scenarios are common enough that Java provides explicit support for dynamic extent with the try...finally and synchronized(...) { ...} statements. However, both of these have to be explicitly written by the caller of an API, at each call site. There’s no way for a file API to use these constructs to automatically enforce that all opened files are eventually closed. The API is limited to providing open and closed and trusting that the caller will use try...finally. The technique I’m about to describe makes it possible to write an an API that removes that burden from the caller.

Continue Reading…