Reputation: 1149
I am building an application in which there i have to format date. For formatting i am using
SimpleDateFormatter class.
As per my knowledge there are three ways to use this class with synchronization
1) create local variable with
new SimpleDateFormatter("MM/dd/yyyy")
2) use synchronized keyword
synchronized(this) {
simpleDateFormatter.format(date); //use static object and then format with synchronization
}
3) use thread local variable with Simple Date Formatter like this
private static ThreadLocal<SimpleDateFormat> outDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("MM/dd/yyyy");
}
I am building web application, where i can receive multiple request and at some point i will be formatting the date.
Now i know that if i have to format more than once in the same thread then ThreadLocal would have been better option.
But according to current scenario every thread will format the date once.
Question-> the whole question boils to the situation. What will be a better option 1 or 3, since option 2 will have performance issue.
As i have to format only once,
---------> are option 1 and option 3 same ?, if they are not, which one is better in my case?
------> is there any other way to make it threadsafe which will not have performance or memory issue(as read in case of ThreadLocal).
I am open to suggestion. Please share your opinions.
Thank you for your time.
Upvotes: 3
Views: 939
Reputation: 728
If your situation is that single thread will have to format the date only once, then there's no point going with ThreadLocal, you can simple create new object every time.
Since the object is creating nevertheless of the situation, in this case using ThreadLocal will be costly and might have memory issue. My suggestion -> go for new Object creation.
I think you are right about synchronization because it will block the threads and since you have to process such a large request of around 10,000 per second.
Another option would be to use Apache Commons Lang's FastDateFormat class as suggested by @Duncan.
Hope this is the answer you are looking for...
Upvotes: 3
Reputation: 1902
SimpleDateFormatter
is a fairly light weight construct. Depending on the volume of call on the SimpleDateFormatter
for parsing and formatting, if you use use synchronized and share a single instance you would end up having loads of blocked threads there.
Its far better and easier to create a new instance and use it when you need.
Upvotes: 0