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
That's exactly what it means. The object itself is accessed by only one thread, and is thus thread-safe. ThreadLocal
objects are a kind of objects that are bound to an only thread
I guess that's what want to say. Like creating a object inside the run
method and not passing the reference to any other instance.
Simple example:
public String s;
public void run() {
StringBuilder sb = new StringBuilder();
sb.append("Hello ").append("world");
s = sb.toString();
}
The StringBuilder instance is thread-safe because it is confined to the thread (that executes this run method)