1717package net .openhft .affinity .impl ;
1818
1919import com .sun .jna .*;
20+ import com .sun .jna .ptr .IntByReference ;
2021import com .sun .jna .ptr .LongByReference ;
2122import net .openhft .affinity .IAffinity ;
2223
@@ -39,10 +40,23 @@ public enum PosixJNAAffinity implements IAffinity {
3940 public static final boolean LOADED ;
4041 private static final Logger LOGGER = Logger .getLogger (PosixJNAAffinity .class .getName ());
4142 private static final String LIBRARY_NAME = Platform .isWindows () ? "msvcrt" : "c" ;
43+ private static final int PROCS = Runtime .getRuntime ().availableProcessors ();
4244
4345 @ Override
4446 public long getAffinity () {
4547 final CLibrary lib = CLibrary .INSTANCE ;
48+ if (PROCS <= 32 ) {
49+ // TODO where are systems with 64+ cores...
50+ final IntByReference cpuset = new IntByReference (0 );
51+ try {
52+ final int ret = lib .sched_getaffinity (0 , Integer .SIZE / 8 , cpuset );
53+ if (ret < 0 )
54+ throw new IllegalStateException ("sched_getaffinity((" + Integer .SIZE / 8 + ") , &(" + cpuset + ") ) return " + ret );
55+ return cpuset .getValue ();
56+ } catch (LastErrorException e ) {
57+ throw new IllegalStateException ("sched_getaffinity((" + Integer .SIZE / 8 + ") , &(" + cpuset + ") ) errorNo=" + e .getErrorCode (), e );
58+ }
59+ }
4660 // TODO where are systems with 64+ cores...
4761 final LongByReference cpuset = new LongByReference (0L );
4862 try {
@@ -58,6 +72,16 @@ public long getAffinity() {
5872 @ Override
5973 public void setAffinity (final long affinity ) {
6074 final CLibrary lib = CLibrary .INSTANCE ;
75+ if (PROCS <= 32 )
76+ try {
77+ final int ret = lib .sched_setaffinity (0 , Integer .SIZE / 8 , new IntByReference ((int ) affinity ));
78+ if (ret < 0 ) {
79+ throw new IllegalStateException ("sched_setaffinity((" + Integer .SIZE / 8 + ") , &(" + affinity + ") ) return " + ret );
80+ }
81+ } catch (LastErrorException e ) {
82+ throw new IllegalStateException ("sched_getaffinity((" + Integer .SIZE / 8 + ") , &(" + affinity + ") ) errorNo=" + e .getErrorCode (), e );
83+ }
84+
6185 try {
6286 //fixme: where are systems with more then 64 cores...
6387 final int ret = lib .sched_setaffinity (0 , Long .SIZE / 8 , new LongByReference (affinity ));
0 commit comments