My Requirements: Get a Timestamp (which is stored in UTC) from a database ResultSet and do it in a thread-safe way.
My code currently looks like this:
Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
while(rs.next())
rs.getTimestamp("utctime",utcCal);
...which works as expected; However seems quite costly to create a new Calendar object for each query (they are very frequent).
I've been looking at Joda-time as a possible replacement, but can't quite figure out how to replace the Calendar with a Joda-time thread-safe object. It would be ideal to create a static final Joda-Time thread-safe Calendar replacement that all queries can use.
Any ideas for a less costly result-set iteration? Since Calendar is not thread safe, I cannot use a single shared instance.
Use synchronized
key word?
synchronized (CALENDAR) {
CALENDAR.setTimeInMillis(System.currentTimeMillis());
while(rs.next()){
rs.getTimestamp("utctime", CALENDAR);
//rest of code
}
}
You could use a ThreadLocal<Calendar>
. This way, each thread will have its own, unique Calendar instance:
public static final ThreadLocal<Calendar> RESULT_SET_CALENDAR = new ThreadLocal<Calendar>() {
@Override
protected Calendar initialValue() {
Calendar calendar = Calendar.getInstance();
// set appropriate timezone
return calendar;
}
};
while (rs.next()) {
Timestamp timestamp = rs.getTimestamp("utctime", RESULT_SET_CALENDAR.get());
...
}
That said, I'm not sure creating a new Calendar each time is so costly compared to the time needed to execute SQL queries. My guess is that you'll have a negligible performance gain, if any.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.