stateful^stateless Thread objects

Q: Say you have a Thread (either from a Runnable or Thread subclass). Is it good practice to remove all fields and make it stateless?

Obviously thread scheduler keeps state of the jvm thread, but application need not know those, and such state info is not exposed to the Thread object. As highlighted in other post, a Thread object is a poor handle on a real jvm thread…

Volatile boolean fields are popular, but must they be a field in the Runnable or Thread subclass?

I think ThreadLocal is implemented as an instance field of a Thread object. See As such it’s a stateful object inside a Thread object.

Let’s bear in mind any non-final field [1] in a Thread or Runnable can be modified by any (jvm) thread — Complex semantics. To simplify modeling[2] and semantics and improve maintainability, I’d avoid custom stateful Thread objects.

[1] or final reference field except String
[2] state ie instance fields are fundamental to OO modeling

Locking is all about state consistency, ie state of domain objects . There’s already enough state to complicate concurrent systems, even if our Thread objects are stateless.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s