1

Can't we use local variables which are thread safe instead of ThreadLocal. and where ThreadLocal is being used. Pls quote some real application examples.

2
  • 2
    Instead of us posting some random example, how about you posting your example? Commented Mar 1, 2015 at 18:41
  • Sometimes you probably can. They aren't the same thing though, so this depends on the behaviour you need in your specific case. Commented Mar 1, 2015 at 18:42

3 Answers 3

4

A typical example is SimpleDateFormat which is not thread safe. In a multi threaded context, two thread safe options are, among others:

private static ThreadLocal<SimpleDateFormat> fmtHolder = new ThreadLocal<SimpleDateFormat>() {
  @Override protected SimpleDateFormat initialValue() {
    return new SimpleDateFormat("dd/MM/yyyy");
  }
};

private void method() {
  SimpleDateFormat fmt = fmtHolder.get();
}

or using a local instance:

private void method() {
  SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
}

The former can be more efficient while the latter is easier to read and reason with.

Sign up to request clarification or add additional context in comments.

Comments

1

A local variable can only be used in the function or block where it is declared, and it ceases to exist when the function returns or the block exits.

You use a ThreadLocal object, usually referenced from a static variable or from an instance variable of a singleton object, when you want static data, but you want each thread to have its own copy.

Comments

0

Thread local variable has different instances in different threads. This allows each thread to have it's own view of the variable that is independent of what other threads see. "Plain" local variable is a single instance and, when accessed in a thread-safe way, will have the same value in all threads.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.