Skip to content
Open
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
20 changes: 12 additions & 8 deletions src/main/java/io/github/jamsesso/jsonlogic/JsonLogic.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

public final class JsonLogic {
private final Map<String, JsonLogicNode> parseCache = new ConcurrentHashMap<>();
private final Map<String, JsonLogicExpression> expressions = new ConcurrentHashMap<>();
private JsonLogicEvaluator evaluator;
private final AtomicReference<JsonLogicEvaluator> evaluator = new AtomicReference<>();

public JsonLogic() {
// Add default operations
Expand Down Expand Up @@ -70,21 +71,24 @@ public String key() {

public JsonLogic addOperation(JsonLogicExpression expression) {
expressions.put(expression.key(), expression);
evaluator = null;

evaluator.set(null);
return this;
}

public Object apply(String json, Object data) throws JsonLogicException {
if (!parseCache.containsKey(json)) {
parseCache.put(json, JsonLogicParser.parse(json));
JsonLogicNode cached = parseCache.get(json);
if (cached == null) {
cached = JsonLogicParser.parse(json);
parseCache.putIfAbsent(json, cached);
}

if (evaluator == null) {
evaluator = new JsonLogicEvaluator(expressions);
JsonLogicEvaluator localEvaluator = this.evaluator.get();
if (localEvaluator == null) {
this.evaluator.compareAndSet(null, new JsonLogicEvaluator(expressions));
localEvaluator = this.evaluator.get();
}
Comment on lines -83 to 85
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could have led to a lost write when an operation is added while one thread is in this if-statement


return evaluator.evaluate(parseCache.get(json), data, "$");
return localEvaluator.evaluate(cached, data, "$");
}

public static boolean truthy(Object value) {
Expand Down