public interface CpuLayout {
int cpus();
int sockets();
int coresPerSocket();
int threadsPerCore();
int socketId(int cpuId);
int coreId(int cpuId);
int threadId(int cpuId);
}
AffinityLock al = AffinityLock.acquireLock();
try {
// do some work locked to a CPU.
} finally {
al.release();
}
try (AffinityLock al = AffinityLock.acquireLock()) {
// do some work while locked to a CPU.
}
try (AffinityLock al = AffinityLock.acquireCore()) {
// do some work while locked to a CPU.
}
public AffinityLock acquireLock(AffinityStrategy... strategies) {
return acquireLock(false, cpuId, strategies);
}
private static final ExecutorService ES = Executors.newFixedThreadPool(4,
new AffinityThreadFactory("bg", SAME_CORE, DIFFERENT_SOCKET, ANY));
for (int i = 0; i < 12; i++)
ES.submit(new Callable<Void>() {
@Override
public Void call() throws InterruptedException {
Thread.sleep(100);
return null;
}
});
Thread.sleep(200);
System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks());
ES.shutdown();
ES.awaitTermination(1, TimeUnit.SECONDS);
The assignment of CPUs is
0: CPU not available
1: Reserved for this application
2: Reserved for this application
3: Reserved for this application
4: Thread[bg-4,5,main] alive=true
5: Thread[bg-3,5,main] alive=true
6: Thread[bg-2,5,main] alive=true
7: Thread[bg,5,main] alive=true
new AffinityThreadFactory("bg", SAME_CORE)
The assignment of CPUs is
0: CPU not available
1: Reserved for this application
2: Reserved for this application
3: Reserved for this application
4: Reserved for this application
5: Reserved for this application
6: Reserved for this application
7: Thread[bg,5,main] alive=true