Skip to content

Concurrent access to ParsedSql cache in NamedParameterJdbcTemplate #24197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

import javax.sql.DataSource;
Expand Down Expand Up @@ -77,13 +78,22 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations

private volatile int cacheLimit = DEFAULT_CACHE_LIMIT;

/** Cache of original SQL String to ParsedSql representation. */
/** Fast access cache for ParsedSqls, returning already cached instances without a global lock */
private final Map<String, ParsedSql> parsedSqlAccessCache = new ConcurrentHashMap<>(DEFAULT_CACHE_LIMIT);

/** Cache of original SQL String to ParsedSql representation, synchronized for creation */
@SuppressWarnings("serial")
private final Map<String, ParsedSql> parsedSqlCache =
private final Map<String, ParsedSql> parsedSqlCreationCache =
new LinkedHashMap<String, ParsedSql>(DEFAULT_CACHE_LIMIT, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, ParsedSql> eldest) {
return size() > getCacheLimit();
if (size() > getCacheLimit()) {
parsedSqlAccessCache.remove(eldest.getKey());
return true;
}
else {
return false;
}
}
};

Expand Down Expand Up @@ -429,9 +439,19 @@ protected ParsedSql getParsedSql(String sql) {
if (getCacheLimit() <= 0) {
return NamedParameterUtils.parseSqlStatement(sql);
}
synchronized (this.parsedSqlCache) {
return this.parsedSqlCache.computeIfAbsent(sql, NamedParameterUtils::parseSqlStatement);

ParsedSql parsedSql = this.parsedSqlAccessCache.get(sql);
if (parsedSql == null) {
synchronized (this.parsedSqlCreationCache) {
parsedSql = this.parsedSqlCreationCache.get(sql);
if (parsedSql == null) {
parsedSql = NamedParameterUtils.parseSqlStatement(sql);
this.parsedSqlAccessCache.put(sql, parsedSql);
this.parsedSqlCreationCache.put(sql, parsedSql);
}
}
}
return parsedSql;
}

/**
Expand Down