Archive for June, 2013

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…

Threads, Line-Synchronization, and OutputStream: ThreadLocals and Java I/O

Posted Jun 27 2013 by in Java with 3 Comments

The other day, our team ran across an interesting design problem related to Java synchronization. Without getting into the details of why this problem came up, the gist of it was that we had to somehow to write a synchronization wrapper around OutputStream. (Well, technically, it was a BufferedWriter…but the issue is the same.) This wrapper needed to correctly allows multiple unsynchronized writer threads to write to an underlying writer, each thread atomically writing lines of text. We wound up managing to avoid having to do this by changing our interface, but the solution to the OutputStream problem still provides an interesting look at a lesser-known aspect of the Java Runtime: ThreadLocal variables.

Continue Reading…

Custom jQuery Functions

Often, I’ll want to create a custom jQuery function to manipulate HTML elements in an application-specific manner. As a simple example, let’s say I want to create a type of textarea that starts out short, but gets taller when i click on the field. I want to create a library to manipulate existing textareas, because I don’t want to go into each and every textarea to add onfocus and onblur code. Here’s how to do it:

Continue Reading…