Skip to content

Commit

Permalink
Revert "Simplified genre matcher setup."
Browse files Browse the repository at this point in the history
This reverts commit e5a5675.
  • Loading branch information
RillingDev committed Dec 26, 2023
1 parent e2c95c7 commit 258fed8
Showing 1 changed file with 27 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
Expand All @@ -19,11 +20,22 @@ public class GenreMatcherService {

private static final Logger LOGGER = LoggerFactory.getLogger(GenreMatcherService.class);

private final CanonicalStringMatcher canonicalStringMatcher;
private static final StringVariantChecker STRING_VARIANT_CHECKER;

static {
Set<String> delimiters = Set.of("-", " ", " and ", " & ");
Collator collator = Collator.getInstance(Locale.ROOT);
collator.setStrength(Collator.PRIMARY);
STRING_VARIANT_CHECKER = new StringVariantChecker(delimiters, collator);
}

private final AtomicReference<CanonicalStringMatcher> canonicalStringMatcherRef = new AtomicReference<>(null);

private final GenreRepository genreRepository;


GenreMatcherService(GenreRepository genreRepository) {
canonicalStringMatcher = createCanonicalStringMatcher(genreRepository.findGenreNames());
this.genreRepository = genreRepository;
}

/**
Expand All @@ -40,7 +52,7 @@ public Set<String> match(Set<String> unmatchedGenres) {
}

Set<String> matches = unmatchedGenres.stream()
.map(canonicalStringMatcher::canonicalize)
.map(getCanonicalStringMatcher()::canonicalize)
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableSet());

Expand All @@ -50,12 +62,17 @@ public Set<String> match(Set<String> unmatchedGenres) {
}


private static CanonicalStringMatcher createCanonicalStringMatcher(Set<String> canonicalGenreNames) {
Set<String> delimiters = Set.of("-", " ", " and ", " & ");
Collator collator = Collator.getInstance(Locale.ROOT);
collator.setStrength(Collator.PRIMARY);
StringVariantChecker stringVariantChecker = new StringVariantChecker(delimiters, collator);

return new CanonicalStringMatcher(canonicalGenreNames, stringVariantChecker);
private CanonicalStringMatcher getCanonicalStringMatcher() {
/*
* It is possible for two threads to concurrently try to initialize the string matcher.
* If that happens, the first one wins, with any further initialization still starting but never being applied.
*/
if (canonicalStringMatcherRef.get() == null) {
Set<String> canonicalGenres = genreRepository.findGenreNames();
CanonicalStringMatcher canonicalStringMatcher = new CanonicalStringMatcher(canonicalGenres,
STRING_VARIANT_CHECKER);
canonicalStringMatcherRef.compareAndSet(null, canonicalStringMatcher);
}
return canonicalStringMatcherRef.get();
}
}

0 comments on commit 258fed8

Please sign in to comment.