Skip to content

Instantly share code, notes, and snippets.

@mtopolnik
Created June 3, 2015 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtopolnik/8bf825ecf84279cb9b09 to your computer and use it in GitHub Desktop.
Save mtopolnik/8bf825ecf84279cb9b09 to your computer and use it in GitHub Desktop.
CpuConsumer (helper in JUnit testing that creates background CPU load)
private static final CpuConsumer cpuConsumer = new CpuConsumer();
@BeforeClass
public static void prepareCpuConsumer() {
cpuConsumer.getReady();
}
private static class CpuConsumer {
final int taskCount = 2 * Runtime.getRuntime().availableProcessors();
volatile CountDownLatch workerLatch = new CountDownLatch(1);
volatile CountDownLatch clientLatch = new CountDownLatch(0);
void pause() {
if (workerLatch.getCount() == 0) {
workerLatch = new CountDownLatch(1);
}
}
void play() throws InterruptedException {
clientLatch = new CountDownLatch(taskCount);
workerLatch.countDown();
assertOpenEventually(clientLatch);
}
void getReady() {
final ExecutorService ex = Executors.newFixedThreadPool(taskCount);
for (int i = 0; i < taskCount; i++) {
ex.execute(new Runnable() {
double d;
@Override public void run() {
final Random rnd = new Random();
while (true) {
try {
workerLatch.await();
clientLatch.countDown();
} catch (InterruptedException e) {
System.err.println("CPU consumer interrupted: "+d);
return;
}
d *= Math.pow(1.001, Math.sqrt(rnd.nextInt(100) + 2));
if (d > 1e48) {
d = 1;
}
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment