JDBC - Null Check Close功能

时间:2012-10-04 05:17:22

标签: java jdbc

背景

我正在使用和关闭大量的Prepared / Callable语句和ResultSet,因此我在finally部分中创建了一个全局静态方法来清理。

很明显,大部分时间都不能为空,我只想确保添加空检查而不是立即关闭。

到目前为止,使用这种方法完全没有问题,但这个线程安全吗? 如果没有,我是否需要使用synchronized方法而不是纯静态方法?

用法其他线程类

private PreparedStatement psUpdate = null;
try {....}
catch(Exception e) {...}
finally
{
    Utils.NullCheckClose(this.psUpdate, this.getProcName());
}

声明实用程序类

public static void NullCheckClose(PreparedStatement temp, String threadname)
{
    try
    {
        if(temp != null)
            temp.close();
    }
    catch(Exception msg)
    {
        Logger.erLog(msg, threadname);
    }
    finally
    {
        temp = null;
    }
}

public static void NullCheckClose(CallableStatement temp, String threadname)
{
    try
    {
        if(temp != null)
            temp.close();
    }
    catch(Exception msg)
    {
        Logger.erLog(msg, threadname);
    }
    finally
    {
        temp = null;
    }
}

public static void NullCheckClose(ResultSet temp, String threadname)
{
    try
    {
        if(temp != null)
            temp.close();
    }
    catch(Exception msg)
    {
        Logger.erLog(msg, threadname);
    }
    finally
    {
        temp = null;
    }
}

2 个答案:

答案 0 :(得分:1)

没有。你没有使用方法的状态。 共享状态时需要同步。 Utils不存储参数值,然后对它们进行操作,它只对它们进行操作,因此不需要同步。

this.psUpdate需要同步,因为它是对象的状态。您应该尝试将其删除成员变量

Utils.NullCheckClose(this.psUpdate, this.getProcName());,<---this.psUpdate try to remove its as a member variable.

最好将PreparedStatementCallableStatement初始化为局部变量而不是成员变量。

答案 1 :(得分:1)

当您需要在线程之间共享数据时,会出现线程安全问题,那么您必须注意原子性,可见性等。
但在这种情况下,没有共享的数据,此方法仅对参数进行操作。所以它的线程安全。