Created
June 3, 2015 10:12
-
-
Save mtopolnik/8bf825ecf84279cb9b09 to your computer and use it in GitHub Desktop.
CpuConsumer (helper in JUnit testing that creates background CPU load)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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