javaweakhashmap

Cache Invalidation while Getting from WeakHashMap


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?


Solution

  • Technically it is but it's extremely rare. The solution is quite simple though:

    If you want to use the value checked in the if, that wasn't null, you can just assign it in the if, so you don't need to retrieve it from cache again in the else:

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