Apache JXPath 对于编译好的表达式,是采用软引用方式进行缓存的,以此降低对xpath表达式编译的开销。直接上代码了:
private Expression compileExpression(String xpath) {
Expression expr;
synchronized (compiled) {
if (USE_SOFT_CACHE) {
expr = null;
SoftReference ref = (SoftReference) compiled.get(xpath);
if (ref != null) {
expr = (Expression) ref.get();
}
}
else {
expr = (Expression) compiled.get(xpath);
}
}
if (expr != null) {
return expr;
}
expr = (Expression) Parser.parseExpression(xpath, getCompiler());
synchronized (compiled) {
if (USE_SOFT_CACHE) {
if (cleanupCount++ >= CLEANUP_THRESHOLD) {
Iterator it = compiled.entrySet().iterator();
while (it.hasNext()) {
Entry me = (Entry) it.next();
if (((SoftReference) me.getValue()).get() == null) {
it.remove();
}
}
cleanupCount = 0;
}
compiled.put(xpath, new SoftReference(expr));
}
else {
compiled.put(xpath, expr);
}
}
return expr;
}