Java ResultSet.getTimestamp使用日历&螺纹安全 [英] Java ResultSet.getTimestamp using Calendar & Thread safety

查看:479
本文介绍了Java ResultSet.getTimestamp使用日历&螺纹安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求:
从数据库ResultSet中获取时间戳记(以UTC存储),并以线程安全的方式执行。

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).

我一直在查看 Joda-time 作为一个可能的替代,但不能完全弄清楚如何替换日历与Joda时间线程安全目的。这将是理想的创建一个静态的最终Joda-Time线程安全日历替换,所有查询都可以使用。

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.

推荐答案

您可以使用 ThreadLocal< Calendar> 。这样,每个线程将有自己的,唯一的日历实例:

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());
    ...
}

每次新的日历与执行SQL查询所需的时间相比是如此昂贵。我的猜测是,如果有的话,你的绩效增益可以忽略不计。

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.

这篇关于Java ResultSet.getTimestamp使用日历&amp;螺纹安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆