Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cost effectiveness of ThreadLocal Variable

Tags:

java

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.

like image 566
rakhi Avatar asked Oct 23 '25 16:10

rakhi


2 Answers

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.

like image 137
Curious Techie Avatar answered Oct 26 '25 06:10

Curious Techie


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?

like image 30
Amol Raje Avatar answered Oct 26 '25 05:10

Amol Raje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!