0

I cache database connection objects via WeakHashMap as like:

    Connection conn;
    if (connectionCache.get(jdbc.getConnectionURL()) == null) {
        conn = DriverManager.getConnection(jdbc.getConnectionURL(), jdbc.getUsername(), jdbc.getPassword());
        connectionCache.put(jdbc.getConnectionURL(), conn);
    } else {
        conn = connectionCache.get(jdbc.getConnectionURL());
    }

Is it possible:

If statement is checked and seen that there is already an object at cache and before running else statement cache is invalidated?

4

1 回答 1

0

从技术上讲,它是但它非常罕见。解决方案非常简单:

如果你想使用在 if 中检查的值,它不为 null,你可以在 if 中分配它,这样你就不需要在 else 中再次从缓存中检索它:

    Connection conn;
    if ((conn = connectionCache.get(jdbc.getConnectionURL())) == null) {
        conn = DriverManager.getConnection(jdbc.getConnectionURL(), jdbc.getUsername(), jdbc.getPassword());
        connectionCache.put(jdbc.getConnectionURL(), conn);
    }
于 2016-12-30T12:56:29.457 回答