4

How does ThreadLocal variable reduces the cost of creating expensive objects?

For example:

private ThreadLocal<String> myThreadLocal = new ThreadLocal<String>();

In the above line we are creating a ThreadLocal Object which will create an object for thread.But I am not able to understand how can it reduce the cost of creating instances.

rakhi
  • 262
  • 2
  • 8
  • 3
    Because it doesn't? – xiaofeng.li Dec 15 '17 at 04:21
  • 1
    Thread Local are special kind of variable just like instance variable. Thread Local is per thread and it's a nice way to achieve thread safety of expensive-to-create objects.Its not good to use in local scope – Sreejesh K Nair Dec 15 '17 at 04:40
  • ThreadLocal can be expected to increase the cost of creating expensive objects ... since one must be instantiated for each thread. The use of the `ThreadLocal` facility helps you achieve correct programs much, much more than fast ones. – scottb Dec 15 '17 at 05:20

4 Answers4

3

Expensive usually means it'll take a while, but it can also mean it'll take a lot of some other resource.

Just like instance variable is per instance, ThreadLocal variable is per thread. It's a way to achieve thread-saftey for expensive-to-create objects.

For ex. SimpleDateFormat, by making it ThreadLocal you can make it threadsafe. Since that class is expensive it is not good to use it in local scope which requires separate instance on each invocation.

By providing each thread their own copy :

1) number of instance of expensive objects are reduced by reusing fixed number of instances.

2) Thread saftey is achieved without cost of synchronization or immutability.

Curious Techie
  • 185
  • 2
  • 15
1

How does ThreadLocal variable reduces the cost of creating expensive objects?

It does not reduces cost of creating objects the single instance of ThreadLocal can store different values for each thread independently.

The TheadLocal construct allows us to store data that will be accessible only by a specific thread.

Let’s say that we want to have an Integer value that will be bundled with the specific thread:

ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();

Next, when we want to use this value from a thread we only need to call a get() or set() method. Simply put, we can think that ThreadLocal stores data inside of a map – with the thread as the key.

Due to that fact, when we call a get() method on the threadLocalValue we will get an Integer value for the requesting thread:

threadLocalValue.set(1);
Integer result = threadLocalValue.get();

For more infrmation you can see When should I use a ThreadLocal variable?

Amol Raje
  • 928
  • 3
  • 9
  • 16
1

A variable should always be declared in the smallest scope possible but a ThreadLocal provides a much bigger scope and should be used only for variable that is needed across many lexical scopes. As per doc:

These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

So they are used when you have a common code and you want to save state on a per thread basis. An example is provided in doc:

import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

In the above example, the classThreadId generates unique identifiers which is local to each thread which is not changed on subsequent calls. Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection.

How does ThreadLocal variable reduces the cost of creating expensive objects?

Until some benchmark supports this claim I am not sure this is even the case with latest JVMs.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
0

It doesn't reduce any cost of creating instances. You are exactly creating an instance of ThreadLocal by new ThreadLocal(), and when you use myThreadLocal.put("anyString"), it put an instance of String (which is already existing) into the current thread's threadLocals.

muzhou
  • 1
  • 2