Krige Krige - 4 months ago 13
Java Question

Why it's not possible to get the Runnable embedded in a Thread?

As far as I can understand from the

docs, and from other questions posted here on stackoverflow, like "How to access a Runnable object by Thread?" and "Get current instance of Runnable" it's not possible to get a reference of the
Runnable
object embedded in a
Thread
.

A scenario where having this possibility would be useful is when implementing a method, whose signature can't be modified because we are overriding a method defined in another class or interface, and different operations are required to be performed depending on the type of
Runnable
embedded in the current
Thread
.

If we had for example a method called
getRunnable
in the
Thread
class we could do something like this:

if (Thread.currentThread().getRunnable() instanceof Type1) {
// do something...
} else {
// do something else...
}


This could be useful also in situations when we want to ensure the operations contained in a method are executed only by certain threads and not by others.

So I was wondering, is there a specific reason why the Java developers decided to not allow to get the
Runnable
instance from a
Thread
, or is it be a missing feature worth to be notified? If you think there is no reason behind that choice but it's not worth to notify it as missing feature, what strategy would you use in the scenario described above?

Answer

So I was wondering, is there a specific reason why the Java developers decided to not allow to get the Runnable instance from a Thread

It was probably just not a requirement. The Runnable itself should be able to identify its own class so the idea that it needs to get that information is strange. It could also be a protection so that other threads would not have access to the class being running in another thread.

If you need that information I'd recommend defining your own class which implements Runnable and exposing a getRunnable() method or something. Really you should expose specifically the methods/fields that you have access to and not the complete Runnable class.

You could also process the current stack trace to figure out the enclosing Runnable class which is even more of a hack but it would work.