In my servlet, when a request comes in, I create a date object.
Date now = new Date();
I want to perform a cache lookup, and I need to create a helper function that will format the date to:
2012.04.24-10:34
which is: yyyy-MM-dd,HH:mm
I had this using simple date format:
public class DateHelpers {
public static final DateFormat minuteDateFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm", Locale.US);
public static String getDateKey(Date now) {
// use minuteDateFormat to format date
}
}
But I was reading that simple date format isn’t thread-safe.
I am not parsing a string to a dateformat, so maybe there is a better and faster way to do this?
I am taking a date object and formatting it to a string, and it must be thread safe as many requests will be using this DateHelper static method to get the key from the date.
Taking a step back, if you are really pressed for performance, I would avoid formatting the date at all and just use the unix timestamp for key (i.e. System.currentTimeMllis()). If you want to lookup based on existing date object
date.getTime()gives you the timestamp.If you want to round it to a minute, you can int-divide and multiply by 60,000 – it’s way faster and guaranteed threadsafe.
For the cases when I format dates, I ususally either create the date format on demand (it is not that expensive), or I have an pool of utility objects which I explicitly associate with each worker.
The thread local solution will work, but over time it is too easy to lose track of all the TL’s and you end up with code that is more difficult to debug.