From 68b38458bd01723fa7b8f04c8348a4f23fddf1ab Mon Sep 17 00:00:00 2001 From: Marc Philipp Date: Fri, 13 Sep 2024 16:57:04 +0200 Subject: [PATCH] Simplify control flow --- .../support/hierarchical/LockManager.java | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/LockManager.java b/junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/LockManager.java index 95259ee7167d..d6366f06cd39 100644 --- a/junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/LockManager.java +++ b/junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/LockManager.java @@ -10,6 +10,8 @@ package org.junit.platform.engine.support.hierarchical; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; import static java.util.Comparator.comparing; import static java.util.Comparator.naturalOrder; import static java.util.stream.Collectors.groupingBy; @@ -46,14 +48,7 @@ private static Comparator globalKeyFirst() { private final Map locksByKey = new ConcurrentHashMap<>(); ResourceLock getLockForResources(Collection resources) { - if (resources.isEmpty()) { - return NopLock.INSTANCE; - } - if (resources.size() == 1) { - return getLockForResource(getOnlyElement(resources)); - } - List locks = getDistinctSortedLocks(resources); - return new CompositeLock(locks); + return toResourceLock(getDistinctSortedLocks(resources)); } ResourceLock getLockForResource(ExclusiveResource resource) { @@ -68,6 +63,12 @@ else if (GLOBAL_READ_WRITE.equals(resource)) { } private List getDistinctSortedLocks(Collection resources) { + if (resources.isEmpty()) { + return emptyList(); + } + if (resources.size() == 1) { + return singletonList(toLock(getOnlyElement(resources))); + } // @formatter:off Map> resourcesByKey = resources.stream() .sorted(COMPARATOR) @@ -86,4 +87,14 @@ private Lock toLock(ExclusiveResource resource) { return resource.getLockMode() == READ ? lock.readLock() : lock.writeLock(); } + private ResourceLock toResourceLock(List locks) { + switch (locks.size()) { + case 0: + return NopLock.INSTANCE; + case 1: + return new SingleLock(locks.get(0)); + default: + return new CompositeLock(locks); + } + } }