Skip to content

Commit 2eb1744

Browse files
committed
Try to ensure there is always a CpuLayout
1 parent f750455 commit 2eb1744

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

src/main/java/vanilla/java/affinity/AffinityLock.java

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,17 +47,25 @@ public class AffinityLock {
4747
private static AffinityLock[] LOCKS;
4848
private static NavigableMap<Integer, AffinityLock[]> CORES; // set by cpuLayout()
4949
private static final AffinityLock NONE = new AffinityLock(-1, false, false);
50-
private static CpuLayout cpuLayout = null;
50+
private static CpuLayout cpuLayout = new NoCpuLayout(PROCESSORS);
5151

5252
static {
5353
try {
5454
if (new File("/proc/cpuinfo").exists()) {
5555
cpuLayout(VanillaCpuLayout.fromCpuInfo());
5656
} else {
5757
LOCKS = new AffinityLock[PROCESSORS];
58-
for (int i = 0; i < PROCESSORS; i++)
59-
LOCKS[i] = new AffinityLock(i, ((BASE_AFFINITY >> i) & 1) != 0, ((RESERVED_AFFINITY >> i) & 1) != 0);
60-
cpuLayout(new NoCpuLayout(PROCESSORS));
58+
CORES = new TreeMap<Integer, AffinityLock[]>();
59+
for (int i = 0; i < PROCESSORS; i++) {
60+
AffinityLock al = LOCKS[i] = new AffinityLock(i, ((BASE_AFFINITY >> i) & 1) != 0, ((RESERVED_AFFINITY >> i) & 1) != 0);
61+
62+
final int layoutId = al.cpuId;
63+
int logicalCpuId = coreForId(layoutId);
64+
AffinityLock[] als = CORES.get(logicalCpuId);
65+
if (als == null)
66+
CORES.put(logicalCpuId, als = new AffinityLock[1]);
67+
als[cpuLayout.threadId(layoutId)] = al;
68+
}
6169
}
6270
} catch (IOException e) {
6371
LOGGER.log(Level.WARNING, "Unable to load /proc/cpuinfo", e);
@@ -77,6 +85,7 @@ public static void cpuLayout(CpuLayout cpuLayout) {
7785
if (cpuLayout.equals(AffinityLock.cpuLayout))
7886
return;
7987
AffinityLock.cpuLayout = cpuLayout;
88+
System.out.println("Locks= " + cpuLayout.cpus());
8089
LOCKS = new AffinityLock[cpuLayout.cpus()];
8190
int threads = cpuLayout.threadsPerCore();
8291
CORES = new TreeMap<Integer, AffinityLock[]>();
@@ -178,7 +187,7 @@ private static AffinityLock acquireLock(boolean bind, int cpuId, AffinityStrateg
178187
for (AffinityStrategy strategy : strategies) {
179188
// consider all processors except cpu 0 which is usually used by the OS.
180189
// if you have only one core, this library is not appropriate in any case.
181-
for (int i = PROCESSORS - 1; i > 0; i--) {
190+
for (int i = LOCKS.length - 1; i > 0; i--) {
182191
AffinityLock al = LOCKS[i];
183192
if (al.canReserve() && (cpuId < 0 || strategy.matches(cpuId, al.cpuId))) {
184193
al.assignCurrentThread(bind, false);

0 commit comments

Comments
 (0)