Skip to content

Commit

Permalink
Backport 35e9662767cc0a1dea9b5afa2a6d61a85297253c
Browse files Browse the repository at this point in the history
  • Loading branch information
elifaslan1 committed Jun 14, 2024
1 parent 4976dc8 commit 6c51bcd
Showing 1 changed file with 35 additions and 7 deletions.
42 changes: 35 additions & 7 deletions test/jdk/java/util/concurrent/SynchronousQueue/Fairness.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,45 @@

/*
* @test
* @modules java.base/java.util.concurrent:open
* @bug 4992438 6633113
* @summary Checks that fairness setting is respected.
*/

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Fairness {
private static void testFairness(boolean fair,
final BlockingQueue<Integer> q)
private final static VarHandle underlyingTransferQueueAccess;

static {
try {
underlyingTransferQueueAccess =
MethodHandles.privateLookupIn(
SynchronousQueue.class,
MethodHandles.lookup()
).findVarHandle(
SynchronousQueue.class,
"transferer",
Class.forName(SynchronousQueue.class.getName() + "$Transferer")
);
} catch (Exception ex) {
throw new ExceptionInInitializerError(ex);
}
}


private static void testFairness(boolean fair, final SynchronousQueue<Integer> q)
throws Throwable
{
final LinkedTransferQueue<Integer> underlying =
(LinkedTransferQueue<Integer>)underlyingTransferQueueAccess.get(q);

final ReentrantLock lock = new ReentrantLock();
final Condition ready = lock.newCondition();
final int threadCount = 10;
Expand All @@ -53,9 +78,12 @@ private static void testFairness(boolean fair,
} catch (Throwable t) { badness[0] = t; }}};
t.start();
ready.await();
// Probably unnecessary, but should be bullet-proof
while (t.getState() == Thread.State.RUNNABLE)
// Wait until previous put:ing thread is provably parked
while (underlying.size() < (i + 1))
Thread.yield();

if (underlying.size() > (i + 1))
throw new Error("Unexpected number of waiting producers: " + i);
}
for (int i = 0; i < threadCount; i++) {
int j = q.take();
Expand All @@ -68,8 +96,8 @@ private static void testFairness(boolean fair,
}

public static void main(String[] args) throws Throwable {
testFairness(false, new SynchronousQueue<Integer>());
testFairness(false, new SynchronousQueue<Integer>(false));
testFairness(true, new SynchronousQueue<Integer>(true));
testFairness(false, new SynchronousQueue<>());
testFairness(false, new SynchronousQueue<>(false));
testFairness(true, new SynchronousQueue<>(true));
}
}

0 comments on commit 6c51bcd

Please sign in to comment.