Sunday, 24 April 2016

In which scenario ThreadLocal is used ?


Java ThreadLocal is used to create thread's local variables.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread.

Values stored in Thread Local can be accessed from anywhere inside that thread.
If a thread calls methods from several classes, then all the methods can see the Thread Local variable set by other methods.

Each thread will have it's own Thread Local variable. One thread cannot access/modify other thread's Thread Local variables.


Scenario to use Thread Local
Consider you have a Servlet which calls some business methods.
You have a requirement to generate a unique transaction ID for each and every request this servlet process and you need to pass this transaction ID to the business methods, for logging purpose.

Solution-1
Pass this transaction ID as a parameter to all the business methods, but it's not a good solution as the code is redundant and unnecessary.

Solution-2 (Using Thread Local)
You can generate a transaction ID (either in servlet or better in a filter) and set it in the Thread Local. 
After this, what ever the business method, that this servlet calls, can access the transaction ID from the thread local.
This servlet might be servicing more that one request at a time.


Since each request is processed in separate thread, the transaction ID will be unique to each thread (local) and will be accessible from all over the thread's execution (global)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.