Created
May 24, 2020 08:14
-
-
Save cleantutorials/537405f69a8a723c1dd840ccc1bd87b1 to your computer and use it in GitHub Desktop.
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
package com.cleantutorials.jconsole.cpu; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.Random; | |
/** | |
* A class to demonstrate the CPU usage in the system space and the user space | |
* as seen in JConsole. Note: Only to demonstrate an example, manually kill the | |
* process if you want to run the example or it can eat up a lot of resources. | |
*/ | |
public class CPUUsage { | |
public static void main(String[] args) throws IOException, InterruptedException { | |
GenerateRandomNumner generator = new GenerateRandomNumner(); | |
generator.setName("Random Generator"); | |
generator.start(); | |
} | |
} | |
/** | |
* Thread that generates lots of random number and write it to a file. | |
* Used in demonstrating the CPU time and User time in JConsole. | |
*/ | |
class GenerateRandomNumner extends Thread { | |
@Override | |
public void run() { | |
File file = new File("random_numbers.txt"); | |
Random rand = new Random(); | |
try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) { | |
for (int i = 0; i < 10000000; i++) { | |
// Contributes to the time executing calls in user space. | |
String randomNumer = Integer.toString(rand.nextInt()); | |
// Contributes to the time executing calls in kernel space. | |
br.write(randomNumer + ","); | |
// Flush the buffer. | |
br.flush(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment