2626import java .io .Closeable ;
2727import java .io .File ;
2828import java .io .IOException ;
29+ import java .util .BitSet ;
2930
3031/**
3132 * This utility class support locking a thread to a single core, or reserving a whole core for a thread.
@@ -41,8 +42,8 @@ public class AffinityLock implements Closeable {
4142 // TODO It seems like on virtualized platforms .availableProcessors() value can change at
4243 // TODO runtime. We should think about how to adopt to such change
4344 public static final int PROCESSORS = Runtime .getRuntime ().availableProcessors ();
44- public static final long BASE_AFFINITY = AffinitySupport .getAffinity ();
45- public static final long RESERVED_AFFINITY = getReservedAffinity0 ();
45+ public static final BitSet BASE_AFFINITY = AffinitySupport .getAffinity ();
46+ public static final BitSet RESERVED_AFFINITY = getReservedAffinity0 ();
4647 private static final LockInventory LOCK_INVENTORY = new LockInventory (new NoCpuLayout (PROCESSORS ));
4748
4849 static {
@@ -102,17 +103,29 @@ public static CpuLayout cpuLayout() {
102103 return LOCK_INVENTORY .getCpuLayout ();
103104 }
104105
105- private static long getReservedAffinity0 () {
106+ private static BitSet getReservedAffinity0 ()
107+ {
106108 String reservedAffinity = System .getProperty (AFFINITY_RESERVED );
107- if (reservedAffinity == null || reservedAffinity .trim ().isEmpty ()) {
108- long reserverable = ((1 << PROCESSORS ) - 1 ) ^ BASE_AFFINITY ;
109- if (reserverable == 0 && PROCESSORS > 1 ) {
109+ if (reservedAffinity == null || reservedAffinity .trim ().isEmpty ())
110+ {
111+ BitSet reserverable = new BitSet (PROCESSORS );
112+ reserverable .set (0 , PROCESSORS - 1 , true );
113+ reserverable .and (BASE_AFFINITY );
114+ if (reserverable .isEmpty () && PROCESSORS > 1 )
115+ {
110116 LoggerFactory .getLogger (AffinityLock .class ).info ("No isolated CPUs found, so assuming CPUs 1 to {} available." , (PROCESSORS - 1 ));
111- return ((1 << PROCESSORS ) - 2 );
117+ reserverable = new BitSet (PROCESSORS );
118+ // make the first CPU unavailable
119+ reserverable .set (1 , PROCESSORS - 1 , true );
120+ reserverable .set (0 , false );
121+ return reserverable ;
112122 }
113123 return reserverable ;
114124 }
115- return Long .parseLong (reservedAffinity , 16 );
125+
126+ long [] longs = new long [1 ];
127+ longs [0 ] = Long .parseLong (reservedAffinity , 16 );
128+ return BitSet .valueOf (longs );
116129 }
117130
118131 /**
@@ -212,7 +225,11 @@ public void bind(boolean wholeCore) {
212225 LOGGER .info ("Assigning cpu {} to {}" , cpuId , assignedThread );
213226 }
214227 if (cpuId >= 0 )
215- AffinitySupport .setAffinity (1L << cpuId );
228+ {
229+ BitSet affinity = new BitSet ();
230+ affinity .set (cpuId , true );
231+ AffinitySupport .setAffinity (affinity );
232+ }
216233 }
217234
218235 final boolean canReserve () {
0 commit comments