Skip to content

Added tests for edge cases #179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: code-analysis
Choose a base branch
from
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package net.openhft.affinity;

import net.openhft.affinity.impl.VanillaCpuLayout;
import org.junit.Assume;
import org.junit.Test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertTrue;

public class AffinityLockDumpLocksTest extends BaseAffinityTest {

@Test
public void dumpLocksListsThreadsHoldingLocks() throws Exception {
Assume.assumeTrue(new File("/proc/cpuinfo").exists());

AffinityLock.cpuLayout(VanillaCpuLayout.fromCpuInfo());
int nThreads = Math.min(3, Math.max(1, AffinityLock.PROCESSORS - 1));
CountDownLatch acquired = new CountDownLatch(nThreads);
CountDownLatch release = new CountDownLatch(1);
List<Thread> threads = new ArrayList<>();

for (int i = 0; i < nThreads; i++) {
String name = "worker-" + i;
Thread t = new Thread(() -> {
try (AffinityLock lock = AffinityLock.acquireLock()) {
supressUnusedWarning(lock);
acquired.countDown();
release.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, name);
threads.add(t);
t.start();
}

assertTrue("threads failed to acquire locks", acquired.await(5, TimeUnit.SECONDS));

String dump = AffinityLock.dumpLocks();
for (Thread t : threads) {
assertTrue("Missing entry for " + t.getName(), dump.contains(t.getName()));
}

release.countDown();
for (Thread t : threads) {
t.join();
}
}

static void supressUnusedWarning(AutoCloseable c) {
// do nothing
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2016-2025 chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.openhft.affinity;

import net.openhft.affinity.impl.VanillaCpuLayout;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.assertEquals;

/**
* Unit test to verify that releasing an {@link AffinityLock} restores the
* affinity mask back to {@link AffinityLock#BASE_AFFINITY}.
*/
public class AffinityLockReleaseTest extends BaseAffinityTest {

@Test
public void acquireAndReleaseShouldRestoreBaseAffinity() throws Exception {
if (!new File("/proc/cpuinfo").exists()) {
System.out.println("Cannot run affinity test as this system doesn't have a /proc/cpuinfo file");
return;
}

// initialise CPU layout from the running machine so acquireLock works
AffinityLock.cpuLayout(VanillaCpuLayout.fromCpuInfo());

assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity());
AffinityLock lock = AffinityLock.acquireLock();
assertEquals(1, Affinity.getAffinity().cardinality());
lock.release();
assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity());
}
}
49 changes: 44 additions & 5 deletions affinity/src/test/java/net/openhft/affinity/AffinityLockTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import static net.openhft.affinity.AffinityLock.PROCESSORS;
Expand Down Expand Up @@ -300,16 +301,54 @@ public void testAffinityLockDescriptions() {
}

@Test
public void acquireLockWithoutBindingDoesNotChangeAffinity() {
BitSet before = (BitSet) Affinity.getAffinity().clone();
try (AffinityLock lock = AffinityLock.acquireLock(false)) {
assertFalse(lock.isBound());
assertEquals(before, Affinity.getAffinity());
}
assertEquals(before, Affinity.getAffinity());
}

@Test(expected = IllegalArgumentException.class)
public void testTooHighCpuId() {
try (AffinityLock ignored = AffinityLock.acquireLock(123456)) {
assertNotNull(ignored);
AffinityLock.acquireLock(123456);
}

@Test(expected = IllegalArgumentException.class)
public void testNegativeCpuId() {
AffinityLock.acquireLock(-1);
}

@Test
@Test(expected = IllegalArgumentException.class)
public void testTooHighCpuId2() {
try (AffinityLock ignored = AffinityLock.acquireLock(new int[] {123456})) {
assertNotNull(ignored);
AffinityLock.acquireLock(new int[]{123456});
}

@Test(expected = IllegalStateException.class)
public void bindingTwoThreadsToSameCpuThrows() throws InterruptedException {
assumeTrue(Runtime.getRuntime().availableProcessors() > 1);

final AffinityLock lock = AffinityLock.acquireLock(false);
Thread t = new Thread(() -> {
lock.bind();
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
// ignored
}
});
t.start();

while (!lock.isBound()) {
Thread.sleep(10);
}

try {
lock.bind();
} finally {
t.join();
lock.release();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package net.openhft.affinity;

import net.openhft.affinity.impl.VanillaCpuLayout;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.assertEquals;

public class AffinityResetToBaseAffinityTest extends BaseAffinityTest {

@Test
public void resettingShouldRestoreBaseAffinity() throws Exception {
if (!new File("/proc/cpuinfo").exists()) {
System.out.println("Cannot run affinity test as this system doesn't have a /proc/cpuinfo file");
return;
}

// initialise CPU layout from the running machine so acquireLock works
AffinityLock.cpuLayout(VanillaCpuLayout.fromCpuInfo());

assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity());
AffinityLock lock = AffinityLock.acquireLock();
try {
assertEquals(1, Affinity.getAffinity().cardinality());

Affinity.resetToBaseAffinity();
assertEquals(AffinityLock.BASE_AFFINITY, Affinity.getAffinity());
} finally {
lock.release();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package net.openhft.affinity;

import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.*;

public class AffinityThreadFactoryTest extends BaseAffinityTest {

@Before
public void checkLinux() {
Assume.assumeTrue(LockCheck.IS_LINUX);
}

@Test
public void threadsReceiveDistinctCpus() throws InterruptedException {
int available = Math.max(1, AffinityLock.PROCESSORS - 1);
int nThreads = Math.min(4, available);

ExecutorService es = Executors.newFixedThreadPool(nThreads,
new AffinityThreadFactory("test"));

Set<Integer> cpus = ConcurrentHashMap.newKeySet();
CountDownLatch ready = new CountDownLatch(nThreads);
CountDownLatch finished = new CountDownLatch(nThreads);

for (int i = 0; i < nThreads; i++) {
es.submit(() -> {
cpus.add(Affinity.getCpu());
ready.countDown();
try {
ready.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
finished.countDown();
});
}

assertTrue(finished.await(5, TimeUnit.SECONDS));
es.shutdown();
es.awaitTermination(5, TimeUnit.SECONDS);

assertFalse(cpus.contains(-1));
assertEquals(nThreads, cpus.size());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 2016-2025 chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.openhft.affinity.impl;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

import static org.junit.Assert.assertEquals;

public class CpuInfoLayoutMappingTest {

@Test
public void verifyI7CpuInfoMapping() throws IOException {
final InputStream i7 = getClass().getClassLoader().getResourceAsStream("i7.cpuinfo");
VanillaCpuLayout vcl = VanillaCpuLayout.fromCpuInfo(i7);
assertEquals(
"0: CpuInfo{socketId=0, coreId=0, threadId=0}\n" +
"1: CpuInfo{socketId=0, coreId=1, threadId=0}\n" +
"2: CpuInfo{socketId=0, coreId=2, threadId=0}\n" +
"3: CpuInfo{socketId=0, coreId=3, threadId=0}\n" +
"4: CpuInfo{socketId=0, coreId=0, threadId=1}\n" +
"5: CpuInfo{socketId=0, coreId=1, threadId=1}\n" +
"6: CpuInfo{socketId=0, coreId=2, threadId=1}\n" +
"7: CpuInfo{socketId=0, coreId=3, threadId=1}\n",
vcl.toString());
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright 2016-2025 chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.openhft.affinity.impl;

import org.junit.Test;

import java.util.BitSet;

import static org.junit.Assert.assertEquals;

public class UtilitiesTest {

private static String hex(BitSet set, int... bits) {
set.clear();
for (int b : bits) {
set.set(b);
}
return Utilities.toHexString(set);
}

private static String bin(BitSet set, int... bits) {
set.clear();
for (int b : bits) {
set.set(b);
}
return Utilities.toBinaryString(set);
}

@Test
public void testToHexString() {
BitSet set = new BitSet();
assertEquals("", hex(set));
assertEquals("1", hex(set, 0));
assertEquals("10", hex(set, 4));
assertEquals(Long.toHexString(1L << 63), hex(set, 63));
assertEquals("01", hex(set, 64));
assertEquals("101", hex(set, 0, 128));
}

@Test
public void testToBinaryString() {
BitSet set = new BitSet();
assertEquals("", bin(set));
assertEquals("1", bin(set, 0));
assertEquals("10000", bin(set, 4));
assertEquals(Long.toBinaryString(1L << 63), bin(set, 63));
assertEquals("01", bin(set, 64));
assertEquals("101", bin(set, 0, 128));
}
}
Loading