Skip to content

Instantly share code, notes, and snippets.

@parttimenerd
Created September 11, 2024 16:59
Show Gist options
  • Save parttimenerd/f75ad904fba8af42c027e30e65d23d59 to your computer and use it in GitHub Desktop.
Save parttimenerd/f75ad904fba8af42c027e30e65d23d59 to your computer and use it in GitHub Desktop.
Java program that spins up 5*#cores CPU-bound threads
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CpuCoreHog {
public static void main(String[] args) {
// Get the number of available processors (cores)
int cores = Runtime.getRuntime().availableProcessors() * 5;
System.out.println("Running on " + cores + " cores.");
// Create a fixed thread pool with the number of available cores
ExecutorService executorService = Executors.newFixedThreadPool(cores);
// Define the task that will hog the CPU
Runnable task = () -> {
System.out.println("start");
int result = 0;
while (true) {
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
result += (i * j) ^ (i + j) % (i + 1);
result -= (i - j) * (j + 1) / (i + 1);
result ^= (i * 3) + (j * 2) - (i / 2);
}
}
}
};
// Submit the task to all available cores
for (int i = 0; i < cores; i++) {
executorService.submit(task);
}
// Shutdown the executor (though this program will run indefinitely)
executorService.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment