Skip to content

Commit

Permalink
Merge pull request #1228 from CDCgov/chores/add-volatile-keywords
Browse files Browse the repository at this point in the history
Handle warning regarding double locking
  • Loading branch information
luis-pabon-tf authored Aug 8, 2024
2 parents c58d081 + a71dcb7 commit 1cfa840
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
public class TransformationRuleEngine implements RuleEngine {
private String ruleDefinitionsFileName;
final List<TransformationRule> rules = new ArrayList<>();

volatile boolean rulesLoaded = false;
private static final TransformationRuleEngine INSTANCE = new TransformationRuleEngine();

@Inject Logger logger;
Expand All @@ -32,14 +32,14 @@ private TransformationRuleEngine() {}
@Override
public void unloadRules() {
rules.clear();
rulesLoaded = false;
}

@Override
public void ensureRulesLoaded() throws RuleLoaderException {
// Double-checked locking - needed to protect from excessive sync locks
if (rules.isEmpty()) {
synchronized (this) {
if (rules.isEmpty()) {
if (!rulesLoaded) {
synchronized (rules) {
if (!rulesLoaded) {
InputStream resourceStream =
getClass()
.getClassLoader()
Expand All @@ -51,7 +51,8 @@ public void ensureRulesLoaded() throws RuleLoaderException {
}
List<TransformationRule> parsedRules =
ruleLoader.loadRules(resourceStream, new TypeReference<>() {});
this.rules.addAll(parsedRules);
rules.addAll(parsedRules);
rulesLoaded = true;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
public class ValidationRuleEngine implements RuleEngine {
private String ruleDefinitionsFileName;
final List<ValidationRule> rules = new ArrayList<>();

volatile boolean rulesLoaded = false;
private static final ValidationRuleEngine INSTANCE = new ValidationRuleEngine();

@Inject Logger logger;
Expand All @@ -32,14 +32,14 @@ private ValidationRuleEngine() {}
@Override
public void unloadRules() {
rules.clear();
rulesLoaded = false;
}

@Override
public void ensureRulesLoaded() throws RuleLoaderException {
// Double-checked locking - needed to protect from excessive sync locks
if (rules.isEmpty()) {
synchronized (this) {
if (rules.isEmpty()) {
if (!rulesLoaded) {
synchronized (rules) {
if (!rulesLoaded) {
InputStream resourceStream =
getClass()
.getClassLoader()
Expand All @@ -51,7 +51,8 @@ public void ensureRulesLoaded() throws RuleLoaderException {
}
List<ValidationRule> parsedRules =
ruleLoader.loadRules(resourceStream, new TypeReference<>() {});
this.rules.addAll(parsedRules);
rules.addAll(parsedRules);
rulesLoaded = true;
}
}
}
Expand Down

0 comments on commit 1cfa840

Please sign in to comment.