I was reading this article by Brian Goetz. Under the section Don’t start threads from within constructors he says “A special case of the problem in Listing 4 is starting a thread from within a constructor, because often when an object owns a thread, either that thread is an inner class or we pass the this reference to its constructor (or the class itself extends the Thread class). If an object is going to own a thread, it is best if the object provides a start() method, just like Thread does, and starts the thread from the start() method instead of from the constructor. ” What does he mean by “often when an object owns a thread”?
Share
I don’t think Goetz means to be taken too literally about an object owning a thread. He just means the thread was started within some other object’s constructor, so it can access the state of that object possibly before it has a chance to finish getting constructed. There is no formal, meaningful ownership relationship, it’s all contextual. For instance you might say whoever has a reference to the thread is the owner because they can cancel it, but the reference can get passed around, there’s nothing special about the object that first created the thread.
If you read Goetz’ book Java Concurrency in Practice it covers design techniques like thread confinement where the scope of things that a thread interacts with are restricted. Also you can create objects so that only one thread can see them, such as when using a ThreadLocal. So you can design your abstractions to create ownership relationships, but it’s up to you.