When should I use a ThreadLocal variable?
How is it used?
Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables.
It can be used in scenarios like making seperate JDBC connection for each thread when you are not using a Connection Pool.
private static ThreadLocal connectionHolder
= new ThreadLocal() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
When you call getConnection, it will return a connection associated with that thread.The same can be done with other properties like dateformat, transaction context that you don't want to share between threads.
You could have also used local variables for the same, but these resource usually take up time in creation,so you don't want to create them again and again whenever you perform some business logic with them. However, ThreadLocal values are stored in the thread object itself and as soon as the thread is garbage collected, these values are gone too.
This link explains use of ThreadLocal very well.