Thread Confinement

后端 未结 8 645
生来不讨喜
生来不讨喜 2020-12-02 14:43

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

8条回答
  •  时光取名叫无心
    2020-12-02 14:57

    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".

提交回复
热议问题