0

背景

我正在使用和关闭很多 Prepared/Callable Statements 和 ResultSet,所以我在 finally 部分创建了一个全局静态方法来清理。

很明显,大多数时候这些不能为空,我只想确保添加空检查而不是立即关闭。

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

用法其他线程类

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;
    }
}
4

2 回答 2

1

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

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

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

初始化 PreparedStatementCallableStatement作为局部变量比成员变量更好。

于 2012-10-04T05:20:38.350 回答
1

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

于 2012-10-04T05:27:15.920 回答