Java Concurrency Interview

Patterns and antipatterns question 148 of 180 mid

What does thread confinement mean, and what are the three kinds?

Data that only one thread can reach needs no synchronisation at all, which makes confinement the cheapest correct answer available.

Stack confinement is the strongest form: a local variable that never escapes cannot be shared, and the compiler enforces it. Ad-hoc confinement is a convention ("only the UI thread touches this"), which is free and fragile, so it must be documented and ideally asserted. ThreadLocal is confinement with a lifetime, which is useful for a per-thread SimpleDateFormat or a request context, and dangerous in a pool if not removed.

Swing and most UI frameworks are built entirely on ad-hoc confinement, which is why calling a component from a background thread is a bug even though nothing throws.

design confinement

Quiz yourself on Patterns and antipatterns Suggest a correction