当前位置:网站首页>Get current JVM data
Get current JVM data
2022-07-03 22:27:00 【User 2700206】
Get current jvm data
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import org.apache.log4j.Logger;
import com.sun.management.OperatingSystemMXBean;
public class MonitorUtil {
private static final Logger logger = Logger.getLogger(MonitorUtil.class);
// It can be set longer , Prevent reading the cpu Occupancy rate , It's not allowed
private static final int CPUTIME = 5000;
private static final int PERCENT = 100;
private static final int FAULTLENGTH = 10;
/** *//**
* Get the current monitoring object .
*/
public static String getMonitorInfoBean() throws Exception {
int kb = 1024;
// Available memory
long totalMemory = Runtime.getRuntime().totalMemory() / kb;
// The remaining memory
long freeMemory = Runtime.getRuntime().freeMemory() / kb;
// Maximum available memory
long maxMemory = Runtime.getRuntime().maxMemory() / kb;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
// operating system
String osName = System.getProperty("os.name");
// Total physical memory
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
// Remaining physical memory
long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// Physical memory used
long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb
.getFreePhysicalMemorySize())
/ kb;
// Get the total number of threads
ThreadGroup parentThread;
for (parentThread = Thread.currentThread().getThreadGroup(); parentThread
.getParent() != null; parentThread = parentThread.getParent())
;
int totalThread = parentThread.activeCount();
double cpuRatio = 0;
if (osName.toLowerCase().startsWith("windows")) {
cpuRatio = getCpuRatioForWindows();
}
StringBuffer sb = new StringBuffer();
double total = (Runtime.getRuntime().totalMemory()) / (1024.0 * 1024);
double max = (Runtime.getRuntime().maxMemory()) / (1024.0 * 1024);
double free = (Runtime.getRuntime().freeMemory()) / (1024.0 * 1024);
logger.info("Java The maximum amount of memory a virtual machine tries to use ( At present JVM Maximum available memory ) maxMemory(): " + max + "MB<br/>");
logger.info("Java Total memory in the virtual machine ( At present JVM Total amount of memory occupied ) totalMemory(): " + total + "MB<br/>");
logger.info("Java The amount of free memory in a virtual machine ( At present JVM Free memory ) freeMemory(): " + free + "MB<br/>");
logger.info(" because JVM Use physical memory only when memory is needed , therefore freeMemory() The value of is usually very small ,<br/>" +
" and JVM The actual available memory is not equal to freeMemory(), It should be equal to maxMemory() - totalMemory() + freeMemory().<br/>");
logger.info("JVM Actually available memory : " + (max - total + free) + "MB<br/>");
logger.info("cpu Occupancy rate =" + cpuRatio+"/n");
logger.info(" Available memory =" + totalMemory+"/n");
logger.info(" The remaining memory =" + freeMemory+"/n");
logger.info(" Maximum available memory =" + maxMemory+"/n");
logger.info(" operating system =" + osName+"/n");
logger.info(" Total physical memory =" + totalMemorySize + "kb/n");
logger.info(" Remaining physical memory =" + freeMemory + "kb/n");
logger.info(" Physical memory used =" + usedMemory + "kb/n");
logger.info(" Total threads =" + totalThread+ "/n");
return sb.toString();
}
/** *//**
* get CPU Usage rate .
*/
private static double getCpuRatioForWindows() {
try {
String procCmd = System.getenv("windir")
+ "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"
+ "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";
// Fetch process information
long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd));
Thread.sleep(CPUTIME);
long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd));
if (c0 != null && c1 != null) {
long idletime = c1[0] - c0[0];
long busytime = c1[1] - c0[1];
return Double.valueOf(
PERCENT * (busytime) / (busytime + idletime))
.doubleValue();
} else {
return 0.0;
}
} catch (Exception ex) {
ex.printStackTrace();
return 0.0;
}
}
/** *//**
* Read CPU Information .
*/
private static long[] readCpu(final Process proc) {
long[] retn = new long[2];
try {
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line = input.readLine();
if (line == null || line.length() < FAULTLENGTH) {
return null;
}
int capidx = line.indexOf("Caption");
int cmdidx = line.indexOf("CommandLine");
int rocidx = line.indexOf("ReadOperationCount");
int umtidx = line.indexOf("UserModeTime");
int kmtidx = line.indexOf("KernelModeTime");
int wocidx = line.indexOf("WriteOperationCount");
long idletime = 0;
long kneltime = 0;
long usertime = 0;
while ((line = input.readLine()) != null) {
if (line.length() < wocidx) {
continue;
}
// Field order :Caption,CommandLine,KernelModeTime,ReadOperationCount,
// ThreadCount,UserModeTime,WriteOperation
String caption = substring(line, capidx, cmdidx - 1)
.trim();
String cmd = substring(line, cmdidx, kmtidx - 1).trim();
if (cmd.indexOf("wmic.exe") >= 0) {
continue;
}
// log.info("line="+line);
if (caption.equals("System Idle Process")
|| caption.equals("System")) {
idletime += Long.valueOf(
substring(line, kmtidx, rocidx - 1).trim())
.longValue();
idletime += Long.valueOf(
substring(line, umtidx, wocidx - 1).trim())
.longValue();
continue;
}
kneltime += Long.valueOf(
substring(line, kmtidx, rocidx - 1).trim())
.longValue();
usertime += Long.valueOf(
substring(line, umtidx, wocidx - 1).trim())
.longValue();
}
retn[0] = idletime;
retn[1] = kneltime + usertime;
return retn;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
proc.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/** *//**
* because String.subString There are problems in the processing of Chinese characters :
* @param src String to intercept
* @param start_idx Start coordinates ( Include this coordinate )
* @param end_idx Cut off coordinate ( Include this coordinate )
* @return
*/
public static String substring(String src, int start_idx, int end_idx){
byte[] b = src.getBytes();
String tgt = "";
for(int i=start_idx; i<=end_idx; i++){
tgt +=(char)b[i];
}
return tgt;
}
}边栏推荐
- IPhone development swift foundation 09 assets
- DR-AP40X9-A-Qualcomm-IPQ-4019-IPQ-4029-5G-4G-LTE-aluminum-body-dual-band-wifi-router-2.4GHZ-5GHz-QSD
- Mindmanager2022 serial number key decompression installer tutorial
- [Android reverse] application data directory (files data directory | lib application built-in so dynamic library directory | databases SQLite3 database directory | cache directory)
- JS Demo calcule combien de jours il reste de l'année
- Programming language (2)
- Pat grade A - 1164 good in C (20 points)
- This time, thoroughly understand bidirectional data binding 01
- Common problems in multi-threaded learning (I) ArrayList under high concurrency and weird hasmap under concurrency
- China HDI market production and marketing demand and investment forecast analysis report Ⓢ 2022 ~ 2028
猜你喜欢

Cesium terrain clipping draw polygon clipping

3 environment construction -standalone

Pooling idea: string constant pool, thread pool, database connection pool

How can enterprises and developers take advantage of the explosion of cloud native landing?

Leetcode week 4: maximum sum of arrays (shape pressing DP bit operation)

Mysql database - Advanced SQL statement (I)

Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)

Covariance

320. Energy Necklace (ring, interval DP)

User login function: simple but difficult
随机推荐
The difference between SRAM and DRAM
Yyds dry goods inventory Spring Festival "make" your own fireworks
Overview of Yunxi database executor
How to obtain opensea data through opensea JS
How to restore the factory settings of HP computer
[secretly kill little partner pytorch20 days] - [day3] - [example of text data modeling process]
WFC900M-Network_ Card/Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-900M-high-power-Mini-PCIe-Wi-Fi-Mod
2 spark environment setup local
[automation operation and maintenance novice village] flask-2 certification
[dynamic programming] Ji Suan Ke: Suan tou Jun breaks through the barrier (variant of the longest increasing subsequence)
DR-AP40X9-A-Qualcomm-IPQ-4019-IPQ-4029-5G-4G-LTE-aluminum-body-dual-band-wifi-router-2.4GHZ-5GHz-QSD
How to store null value on the disk of yyds dry inventory?
Team collaborative combat penetration tool CS artifact cobalt strike
webAssembly
Buuctf, web:[geek challenge 2019] buyflag
IPhone development swift foundation 08 encryption and security
SDNU_ ACM_ ICPC_ 2022_ Winter_ Practice_ 4th [individual]
How can enterprises and developers take advantage of the explosion of cloud native landing?
Can you draw with turtle?
Pooling idea: string constant pool, thread pool, database connection pool