Created
April 4, 2024 09:04
-
-
Save lyveng/c864fa6aee7e733f4df59a4883bdd2fb to your computer and use it in GitHub Desktop.
Java code to illustrate the regression in Runtime.availableProcessors function
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.atomic.AtomicBoolean; | |
import java.util.concurrent.atomic.AtomicInteger; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
AtomicBoolean stop = new AtomicBoolean(); | |
AtomicInteger count = new AtomicInteger(); | |
int numThreads = 1; | |
String numThreadsEnv = System.getenv("NUM_THREADS"); | |
if (numThreadsEnv != null) { | |
numThreads = Integer.parseInt(numThreadsEnv); | |
} | |
System.out.println("Num of Threads = "+ numThreads); | |
for (int i = 0; i < numThreads; i++) { | |
new Thread(() -> { | |
while (!stop.get()) { | |
Runtime.getRuntime().availableProcessors(); | |
count.incrementAndGet(); | |
} | |
}).start(); | |
} | |
try { | |
int lastCount = 0; | |
while (true) { | |
Thread.sleep(1000); | |
int thisCount = count.get(); | |
System.out.printf("%s calls/sec %n", thisCount - lastCount); | |
lastCount = thisCount; | |
} | |
} | |
finally { | |
stop.set(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment