Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the advantage of ThreadLocal?

 
Venkat Sadasivam
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to hear the advantages and disadvantages of ThreadLocal?

Note: I know theoretical definition. I would like to hear practical examples where you have applied ThreadLocal.
 
arulk pillai
Author
Ranch Hand
Posts: 3387
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can store values in a threadsafe manner. Each thread will have its own threadlocal. For example you can store the Hibernate Session in a threadlocal and reuse it for the same thread rather than creating a new Session each time.
 
Venkat Sadasivam
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I have seen sample in Hibernate in Action book.

Looking for more practical examples from other JavaRanch experts?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15279
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One common use for ThreadLocal is for SimpleDateFormat objects.

Often, you need to format dates with a certain format, and it's ofcourse a good idea to create the SimpleDateFormat object once (instead of creating a new SimpleDateFormat for every time that you need to format a date). So you might have something like this:

This is going to fail if multiple threads call formatDate(...) at the same time (you might get strange output or exceptions) because SimpleDateFormat is not thread-safe. To make it thread-safe, you can use ThreadLocal:

By doing this, a new SimpleDateFormat object is created for every thread that calls formatDate(), so it will be thread-safe.
[ August 18, 2008: Message edited by: Jesper Young ]
 
Venkat Sadasivam
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking for more examples, please share your experience here on ThreadLocal.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic