Thread Confinement

denniss picture denniss · Jun 7, 2011 · Viewed 10.6k times · Source

I am reading Java Concurrency in Practice and kind of confused with the thread confinement concept. The book says that

When an object is confined to a thread, such usage is automatically thread-safe even if the confined object itself is not

So when an object is confined to a thread, no other thread can have access to it? Is that what it means to be confined to a thread? How does one keep an object confined to a thread?

Edit: But what if I still want to share the object with another thread? Let's say that after thread A finishes with object O, thread B wants to access O. In this case, can O still be confined to B after A is done with it?

Using a local variable is one example for sure but that just means you don't share your object with other thread (AT ALL). In case of JDBC Connection pool, doesn't it pass one connection from one thread to another once a thread is done with that connection (totally clueless about this because I never used JDBC).

Answer

Joachim Sauer picture Joachim Sauer · Jun 7, 2011

So when an object is confined to a thread, no other thread can have access to it?

No, it's the other way around: if you ensure that no other thread has access to an object, then that object is said to be confined to a single thread.

There's no language- or JVM-level mechanism that confines an object to a single thread. You simply have to ensure that no reference to the object escapes to a place that could be accessed by another thread. There are tools that help avoid leaking references, such as the ThreadLocal class, but nothing that ensures that no reference is leaked anywhere.

For example: if the only reference to an object is from a local variable, then the object is definitely confined to a single thread, as other threads can never access local variables.

Similarly, if the only reference to an object is from another object that has already been proven to be confined to a single thread, then that first object is confined to the same thread.

Ad Edit: In practice you can have an object that's only accessed by a single thread at a time during its lifetime, but for which that single thread changes (a JDBC Connection object from a connection pool is a good example).

Proving that such an object is only ever accessed by a single thread is much harder than proving it for an object that's confined to a single thread during its entire life, however.

And in my opinion those objects are never really "confined to a single thread" (which would imply a strong guarantee), but could be said to "be used by a single thread at a time only".