Skip to content

Instantly share code, notes, and snippets.

@larsbutler
Last active August 15, 2022 10:31
Show Gist options
  • Save larsbutler/18b74932be1c848fcaf135251761705c to your computer and use it in GitHub Desktop.
Save larsbutler/18b74932be1c848fcaf135251761705c to your computer and use it in GitHub Desktop.
Check CPU load on multiple cores in a multi-threaded Java process
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class Test {
public static void main(String [] args) {
// Probably this can vary, depending on whether you run from
// command line or from an IDE.
final int startingThreadCount = Thread.activeCount();
System.out.printf("Starting thread count: %d%n", startingThreadCount);
int availCPUs = Runtime.getRuntime().availableProcessors();
System.out.printf(
"Available CPUs: %d%n",
availCPUs);
int threads = availCPUs * 2;
System.out.printf("Starting %d threads...%n", threads);
for (int i = 0; i < threads; i++) {
Task t = new Task();
new Thread(t).start();
}
Thread monitor = new Thread(new Runnable() {
public void run() {
OperatingSystemMXBean OS = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
while(Thread.activeCount() > startingThreadCount + 1) {
System.out.println("Still processing...");
System.out.printf(
"Active thread count: %d%n",
Thread.activeCount());
System.out.printf(
"CPU load (of all CPUs): %.2f%%%n",
OS.getProcessCpuLoad() * 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Done!");
}
});
monitor.start();
}
}
class Task implements Runnable {
public static final long SAMPLES = 100_000_000L;
/**
* Simple pi approximation based on the Leibniz formula for pi.
* See http://en.wikipedia.org/wiki/Leibniz_formula_for_pi
*/
public void run() {
double pi = 0.0;
// ten million samples
for(long k = 0; k < SAMPLES; k++) {
pi += 4.0 * (Math.pow(-1.0, k) / ((2.0 * k) + 1));
}
System.out.printf(
"Thread: %s. Result: %f%n",
Thread.currentThread().getName(),
pi);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment