Java ResultSet.getTimestamp using Calendar & Thread safety

我怕爱的太早我们不能终老 提交于 2019-12-11 07:56:16

问题


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.


回答1:


Use synchronized key word?

        synchronized (CALENDAR) {
        CALENDAR.setTimeInMillis(System.currentTimeMillis());
        while(rs.next()){
            rs.getTimestamp("utctime", CALENDAR);
            //rest of code
        } 
    }



回答2:


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.



来源:https://stackoverflow.com/questions/17949289/java-resultset-gettimestamp-using-calendar-thread-safety

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!