Skip to content

Commit fa423ea

Browse files
committed
Refactor CPU ID validation in AffinityLock and enhance test cases for invalid inputs
1 parent 2d931c3 commit fa423ea

2 files changed

Lines changed: 17 additions & 10 deletions

File tree

affinity/src/main/java/net/openhft/affinity/AffinityLock.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,17 @@ public static AffinityLock acquireLock(boolean bind) {
186186
* @return A handle for an affinity lock.
187187
*/
188188
public static AffinityLock acquireLock(int cpuId) {
189-
checkCpuId(cpuId);
189+
if (isInvalidCpuId(cpuId))
190+
return LOCK_INVENTORY.noLock();
190191
return acquireLock(true, cpuId, AffinityStrategies.ANY);
191192
}
192193

193-
private static void checkCpuId(int cpuId) {
194+
private static boolean isInvalidCpuId(int cpuId) {
194195
if (cpuId < 0 || cpuId >= PROCESSORS) {
195196
LOGGER.warn("cpuId must be between 0 and {}: {}", PROCESSORS - 1, cpuId);
197+
return true;
196198
}
199+
return false;
197200
}
198201

199202
/**
@@ -207,7 +210,7 @@ private static void checkCpuId(int cpuId) {
207210
*/
208211
public static AffinityLock acquireLock(int[] cpus) {
209212
for (int cpu : cpus) {
210-
checkCpuId(cpu);
213+
if (isInvalidCpuId(cpu)) continue;
211214
AffinityLock lock = tryAcquireLock(true, cpu);
212215
if (lock != null) {
213216
LOGGER.info("Acquired lock on CPU {}", cpu);

affinity/src/test/java/net/openhft/affinity/AffinityLockTest.java

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -310,19 +310,22 @@ public void acquireLockWithoutBindingDoesNotChangeAffinity() {
310310
assertEquals(before, Affinity.getAffinity());
311311
}
312312

313-
@Test(expected = IllegalArgumentException.class)
313+
@Test
314314
public void testTooHighCpuId() {
315-
AffinityLock.acquireLock(123456);
316-
}
315+
AffinityLock lock = AffinityLock.acquireLock(123456);
316+
assertFalse(lock.isBound());
317+
}
317318

318-
@Test(expected = IllegalArgumentException.class)
319+
@Test
319320
public void testNegativeCpuId() {
320-
AffinityLock.acquireLock(-1);
321+
AffinityLock lock = AffinityLock.acquireLock(-1);
322+
assertFalse(lock.isBound());
321323
}
322324

323-
@Test(expected = IllegalArgumentException.class)
325+
@Test
324326
public void testTooHighCpuId2() {
325-
AffinityLock.acquireLock(new int[]{123456});
327+
AffinityLock lock = AffinityLock.acquireLock(new int[]{-1, 123456});
328+
assertFalse(lock.isBound());
326329
}
327330

328331
@Test(expected = IllegalStateException.class)
@@ -341,6 +344,7 @@ public void bindingTwoThreadsToSameCpuThrows() throws InterruptedException {
341344
t.start();
342345

343346
while (!lock.isBound()) {
347+
//noinspection BusyWait
344348
Thread.sleep(10);
345349
}
346350

0 commit comments

Comments
 (0)