Thread Confinement

True to the mission of this site, my first post reflects something for which I forgot the name and had to look up, so in the Javanator hopper it goes. Thread Confinement is a technique for making the use of an object thread-safe by guaranteeing that only one thread ever uses it. This is in contrast to many of the other techniques for engineering thread safety that involve a lot of guarding and synchronizing and general-purpose sweat of the mind.

The simplest way to ensure thread confinement is to write a single-threaded application. Unfortunately, this is harder to do than it sounds. Think you’ve written a single-threaded app? Don’t be so sure. Does your app use Swing? Definitely not single-threaded, then. Just because you haven’t spawned any threads doesn’t mean one of your frameworks hasn’t and frameworks, it seems, are everywhere these days, even for the smallest of tasks.

I first saw the term thread confinement in the book Java Concurrency in Practice. That reference contains a fine description of the technique, and includes subsections on implementing thread confinement using stack confinement, ThreadLocal variables, and ad-hoc techniques.