0

I already have a ThreadLocal object defined as a class Context

class Context {
.....
some existing fields
.....
}
ThreadLocal<Context> = .....

If I have to add a new boolean field to the above Context class, what would be the performance impact for ThreadLocal get() and set() operations?

Vamshi
  • 9
  • 1
  • 1
    Does this answer your question? [Performance of ThreadLocal variable](https://stackoverflow.com/questions/609826/performance-of-threadlocal-variable) – Joe Sep 05 '21 at 07:08
  • None? Keep in mind that it's a reference to the actual object that is stored – Gaël J Sep 05 '21 at 07:11
  • Nil. The size or content of the object has nothing to do with the performance of storing a reference to it. – user207421 Sep 05 '21 at 10:13
  • Please provide enough code so others can better understand or reproduce the problem. – Community Sep 09 '21 at 06:25

1 Answers1

0

The get method of the ThreadLocal class looks like

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
        ...

So whenever we are getting an object from the ThreadLocal, it will get the element from its internally stored map.

Since the get/set method only needs to read/write the object in the map, adding/removing a field in the object's class won't have an effect on the performance.

Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35