0

Can we get back reference to a member variable of a Thread like the way we get for ThreadLocal?

For example, lets say we use a counter variable to counter amount of requests processed by the Thread in a ThreadLocal variable. Consider that we are using a ThreadPool Executer for reusing threads. Now every Thread keeps a reference to a ThreadLocal counter variable and it can increment its own copy after every request. In a similar manner if i have a Member variable inside a Runnable, can i get back a reference to it? The Thread is anyway being reused.

1 Answer 1

1

if i have a Member variable inside a Runnable, can i get back a reference to it?

When you say "a Runnable", you're talking about some object that implements the Runnable interface. There is nothing magic about Runnable and there is nothing magic about a run() method.

The member variables of your Runnable object are just like the member variables of any other object, and your code accesses them in the same way.


P.S., Usually, when you see ThreadLocal in a program, it means

  • The program used to be single-threaded,
  • It keeps a lot of its state in static variables,
  • Somebody added multi-threading as an after-thought, and
  • It makes sense for some of that static state to be duplicated for each thread.

I would almost never use ThreadLocal in a new program, because I try hard not to write any code that depends on static variables, and if you're using ThreadLocal for non-static data, you're probably making your program way more complicated than it needs to be.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.