Created
September 11, 2024 16:59
-
-
Save parttimenerd/f75ad904fba8af42c027e30e65d23d59 to your computer and use it in GitHub Desktop.
Java program that spins up 5*#cores CPU-bound threads
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
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