When and how should I use a ThreadLocal variable?
When and how should I use a ThreadLocal variable?
When should I use a ThreadLocal
variable?
How is it used?
Answer by RichieHindle for When and how should I use a ThreadLocal variable?
The documentation says it very well: "each thread that accesses [a thread-local variable] (via its get or set method) has its own, independently initialized copy of the variable".
You use one when each thread must have its own copy of something. By default, data is shared between threads.
Answer by user100464 for When and how should I use a ThreadLocal variable?
In Java, if you have a datum that can vary per-thread, your choices are to pass that datum around to every method that needs (or may need) it, or to associate the datum with the thread. Passing the datum around everywhere may be workable if all your methods already need to pass around a common "context" variable.
If that's not the case, you may not want to clutter up your method signatures with an additional parameter. In a non-threaded world, you could solve the problem with the Java equivalent of a global variable. In a threaded word, the equivalent of a global variable is a thread-local variable.
Answer by overthink for When and how should I use a ThreadLocal variable?
One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object.
For example:
public class Foo { // SimpleDateFormat is not thread-safe, so give one to each thread private static final ThreadLocal formatter = new ThreadLocal(){ @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd HHmm"); } }; public String formatIt(Date date) { return formatter.get().format(date); } }
Answer by Phil M for When and how should I use a ThreadLocal variable?
Since a ThreadLocal
is a reference to data within a given Thread
, you can end up with classloading leaks when using ThreadLocal
s in application servers which use thread pools. You need to be very careful about cleaning up any ThreadLocal
s you get()
or set()
by using the ThreadLocal
's remove()
method.
If you do not clean up when you're done, any references it holds to classes loaded as part of a deployed webapp will remain in the permanent heap and will never get garbage collected. Redeploying/undeploying the webapp will not clean up each Thread
's reference to your webapp's class(es) since the Thread
is not something owned by your webapp. Each successive deployment will create a new instance of the class which will never be garbage collected.
You will end up with out of memory exceptions due to java.lang.OutOfMemoryError: PermGen space
and after some googling will probably just increase -XX:MaxPermSize
instead of fixing the bug.
If you do end up experiencing these problems, you can determine which thread and class is retaining these references by using Eclipse's Memory Analyzer and/or by following Frank Kieviet's guide and followup.
Update: Re-discovered Alex Vasseur's blog entry that helped me track down some ThreadLocal
issues I was having.
Answer by Neil Coffey for When and how should I use a ThreadLocal variable?
Essentially, when you need a variable's value to depend on the current thread and it isn't convenient for you to attach the value to the thread in some other way (for example, subclassing thread).
A typical case is where some other framework has created the thread that your code is running in, e.g. a servlet container, or where it just makes more sense to use ThreadLocal because your variable is then "in its logical place" (rather than a variable hanging from a Thread subclass or in some other hash map).
On my web site, I have some further discussion and examples of when to use ThreadLocal that may also be of interest.
Some people advocate using ThreadLocal as a way to attach a "thread ID" to each thread in certain concurrent algorithms where you need a thread number (see e.g. Herlihy & Shavit). In such cases, check that you're really getting a benefit!
Answer by Robin for When and how should I use a ThreadLocal variable?
As was mentioned by @unknown (google), it's usage is to define a global variable in which the value referenced can be unique in each thread. It's usages typically entails storing some sort of contextual information that is linked to the current thread of execution.
We use it in a Java EE environment to pass user identity to classes that are not Java EE aware (don't have access to HttpSession, or the EJB SessionContext). This way the code, which makes usage of identity for security based operations, can access the identity from anywhere, without having to explicitly pass it in every method call.
The request/response cycle of operations in most Java EE calls makes this type of usage easy since it gives well defined entry and exit points to set and unset the ThreadLocal.
Answer by Esko Luontola for When and how should I use a ThreadLocal variable?
Many frameworks use ThreadLocals to maintain some context related to the current thread. For example when the current transaction is stored in a ThreadLocal, you don't need to pass it as a parameter through every method call, in case someone down the stack needs access to it. Web applications might store information about the current request and session in a ThreadLocal, so that the application has easy access to them. With Guice you can use ThreadLocals when implementing custom scopes for the injected objects (Guice's default servlet scopes most probably use them as well).
ThreadLocals are one sort of global variables (although slightly less evil because they are restricted to one thread), so you should be careful when using them to avoid unwanted side-effects and memory leaks. Design your APIs so that the ThreadLocal values will always be automatically cleared when they are not anymore needed and that incorrect use of the API won't be possible (for example like this). ThreadLocals can be used to make the code cleaner, and in some rare cases they are the only way to make something work (my current project had two such cases; they are documented here under "Static Fields and Global Variables").
Answer by Jeff Richley for When and how should I use a ThreadLocal variable?
You have to be very careful with the ThreadLocal pattern. There are some major down sides like Phil mentioned, but one that wasn't mentioned is to make sure that the code that sets up the ThreadLocal context isn't "re-entrant."
Bad things can happen when the code that sets the information gets run a second or third time because information on your thread can start to mutate when you didn't expect it. So take care to make sure the ThreadLocal information hasn't been set before you set it again.
Answer by Colselaw for When and how should I use a ThreadLocal variable?
Nothing really new here, but I discovered today that ThreadLocal
is very useful when using Bean Validation in a web application. Validation messages are localized, but by default use Locale.getDefault()
. You can configure the Validator
with a different MessageInterpolator
, but there's no way to specify the Locale
when you call validate
. So you could create a static ThreadLocal
(or better yet, a general container with other things you might need to be ThreadLocal
and then have your custom MessageInterpolator
pick the Locale
from that. Next step is to write a ServletFilter
which uses a session value or request.getLocale()
to pick the locale and store it in your ThreadLocal
reference.
Answer by znlyj for When and how should I use a ThreadLocal variable?
In wabapp server, it may be keep a thread pool, so a ThreadLocal
var should be removed before response to the client, since current thread may be reused by next request.
Answer by Abhijit Gaikwad for When and how should I use a ThreadLocal variable?
ThreadLocal in Java had been introduced on JDK 1.2 but was later generified in JDK 1.5 to introduce type safety on ThreadLocal variable.
ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.
Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn't have any other live references.
ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread.
Read more: http://javarevisited.blogspot.com/2012/05/how-to-use-threadlocal-in-java-benefits.html#ixzz2XltgbHTK
Answer by Ian Ringrose for When and how should I use a ThreadLocal variable?
Caching, sometime you have to calculate the same value lots of time so by storing the last set of inputs to a method and the result you can speed the code up. By using Thread Local Storage you avoid having to think about locking.
Answer by Vishnu for When and how should I use a ThreadLocal variable?
Thread Local is used to bind an object to a Thread. You can say.. each thread has their own copy of a specific object. To know more about threadlocal. http://javaworldwide.blogspot.in/2015/08/threadlocal-in-java.html
Answer by infoj for When and how should I use a ThreadLocal variable?
Two use cases where threadlocal variable can be used -
1- When we have a requirement to associate state with a thread (e.g., a user ID or Transaction ID). That usually happens with a web application that every request going to a servlet has a unique transactionID associated with it.
// This class will provide a thread local variable which // will provide a unique ID for each thread 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 threadId = ThreadLocal.withInitial(()-> {return nextId.getAndIncrement();}); // Returns the current thread's unique ID, assigning it if necessary public static int get() { return threadId.get(); } }
Note that here the method withInitial is implemented using lambda expression.
2- Another use case is when we want to have a thread safe instance and we don't want to use synchronization as the performance cost with synchronization is more. One such case is when SimpleDateFormat is used. Since SimpleDateFormat is not thread safe so we have to provide mechanism to make it thread safe.
public class ThreadLocalDemo1 implements Runnable { // threadlocal variable is created private static final ThreadLocal dateFormat = new ThreadLocal(){ @Override protected SimpleDateFormat initialValue(){ System.out.println("Initializing SimpleDateFormat for - " + Thread.currentThread().getName() ); return new SimpleDateFormat("dd/MM/yyyy"); } }; public static void main(String[] args) { ThreadLocalDemo1 td = new ThreadLocalDemo1(); // Two threads are created Thread t1 = new Thread(td, "Thread-1"); Thread t2 = new Thread(td, "Thread-2"); t1.start(); t2.start(); } @Override public void run() { System.out.println("Thread run execution started for " + Thread.currentThread().getName()); System.out.println("Date formatter pattern is " + dateFormat.get().toPattern()); System.out.println("Formatted date is " + dateFormat.get().format(new Date())); } }
Read more here - http://netjs.blogspot.in/2015/07/when-and-how-to-use-thread-local-class-in-java.html
Answer by Rakesh Chauhan for When and how should I use a ThreadLocal variable?
There is very good example in book Java Concurrency in Practice. Where he explains how Thread confinement is one of the simplest ways to achieve thread safety and Thread Local is more formal means of maintaining thread confinement. In the end he also explain how people can abuse it by using it as global variables.
I have copied the text from the mentioned book but code 3.10 is missing as it is not much important to understand where Thread Local should be use.
Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables. For example, a single-threaded application might maintain a global database connection that is initialized at startup to avoid having to pass a Connection to every method. Since JDBC connections may not be thread-safe, a multithreaded application that uses a global connection without additional coordination is not thread-safe either. By using a ThreadLocal to store the JDBC connection, as in ConnectionHolder in Listing 3.10, each thread will have its own connection.
ThreadLocal is widely used in implementing application frameworks. For example, J2EE containers associate a transaction context with an executing thread for the duration of an EJB call. This is easily implemented using a static Thread-Local holding the transaction context: when framework code needs to determine what transaction is currently running, it fetches the transaction context from this ThreadLocal. This is convenient in that it reduces the need to pass execution context information into every method, but couples any code that uses this mechanism to the framework.
It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating ?hidden? method arguments. Like global variables, thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.
Answer by Kanagavelu Sugumar for When and how should I use a ThreadLocal variable?
Each Thread
in java contains ThreadLocalMap
in it.
Where
Key = ThreadLocal object shared across threads. value = Mutable object which has to be used synchronously.
Now create a wrapper class on mutable object like below, ensure that class contains ThreadLocal instance with or without initialValue()
.
class SimpleDateFormatInstancePerThread { private static final ThreadLocal dateFormatHolder = new ThreadLocal() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd") { UUID id = UUID.randomUUID(); @Override public String toString() { return id.toString(); }; }; System.out.println("Creating SimpleDateFormat instance " + dateFormat +" for Thread : " + Thread.currentThread().getName()); return dateFormat; } }; /* * Every time there is a call for DateFormat, ThreadLocal will return calling * Thread's copy of SimpleDateFormat */ public static DateFormat getDateFormatter() { return dateFormatHolder.get(); } public static void cleanup() { dateFormatHolder.remove(); } }
Now wrapper.getDateFormatter()
will call threadlocal.get()
and that will check the currentThread.threadLocalMap
contains this (threadlocal) instance.
If yes return the value (SimpleDateFormat) for corresponding threadlocal instance
else add the map with this threadlocal instance, initialValue().
Herewith thread safety achieved on this mutable class; by each thread is working with its own mutable instance but with same ThreadLocal instance. Means All the thread will share the same ThreadLocal instance as key, but different SimpleDateFormat instance as value.
https://github.com/skanagavelu/yt.tech/blob/master/src/ThreadLocalTest.java
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 71
0 comments:
Post a Comment