• 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: 3404
  • 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
Sheriff
Posts: 15758
74
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.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!