jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes What is the advantage of ThreadLocal? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What is the advantage of ThreadLocal?" Watch "What is the advantage of ThreadLocal?" New topic
Author

What is the advantage of ThreadLocal?

Venkat Sadasivam
Ranch Hand

Joined: May 10, 2008
Posts: 139
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.


“Any fool can write code that a computer can understand. Good programmers write code that humans can understand. ”<br>
-Martin Fowler
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3219
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.


Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
Venkat Sadasivam
Ranch Hand

Joined: May 10, 2008
Posts: 139
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

Joined: Aug 16, 2005
Posts: 14107
    
  16

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 ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Venkat Sadasivam
Ranch Hand

Joined: May 10, 2008
Posts: 139
Looking for more examples, please share your experience here on ThreadLocal.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is the advantage of ThreadLocal?