Skip to content

Commit 3e7aef9

Browse files
committed
peter-lawrey#21 Ensure un-bound affinity locks are not assigned more than once.
1 parent 75003e9 commit 3e7aef9

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,12 @@ else if (al.base)
238238
this.reserved = reserved;
239239
}
240240

241+
/**
242+
* Assigning the current thread has a side effect of preventing the lock being used again until it is released.
243+
*
244+
* @param bind whether to bind the thread as well
245+
* @param wholeCore whether to reserve all the thread in the same core.
246+
*/
241247
private void assignCurrentThread(boolean bind, boolean wholeCore) {
242248
assignedThread = Thread.currentThread();
243249
if (bind)
@@ -343,4 +349,8 @@ protected void finalize() throws Throwable {
343349
}
344350
super.finalize();
345351
}
352+
353+
public int cpuId() {
354+
return cpuId;
355+
}
346356
}

src/test/java/vanilla/java/affinity/AffinityLockTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.io.IOException;
2323

2424
import static org.junit.Assert.assertEquals;
25+
import static org.junit.Assert.assertNotSame;
2526

2627
/**
2728
* @author peter.lawrey
@@ -128,4 +129,17 @@ public void assignReleaseThread() throws IOException {
128129
assertEquals(AffinityLock.BASE_AFFINITY, AffinitySupport.getAffinity());
129130
}
130131

132+
@Test
133+
public void testIssue21() {
134+
AffinityLock al = AffinityLock.acquireLock();
135+
AffinityLock alForAnotherThread = al.acquireLock(AffinityStrategies.ANY);
136+
AffinityLock alForAnotherThread2 = al.acquireLock(AffinityStrategies.ANY);
137+
assertNotSame(alForAnotherThread, alForAnotherThread2);
138+
assertNotSame(alForAnotherThread.cpuId(), alForAnotherThread2.cpuId());
139+
140+
al.release();
141+
alForAnotherThread.release();
142+
alForAnotherThread2.release();
143+
}
144+
131145
}

0 commit comments

Comments
 (0)