JVM parameter types
Runtime JVM parameter viewing
Standard parameters
These parameters are basically unchanged and relatively stable,
Such as:
-help -server -client -version -showversion -cp -classpath
Eg:
xxx@192 ~ % java -version
java version "1.8.0 comes with _241"
Java(TM) SE Runtime Environment (build 1.8. 0 _241-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.241-b07, mixed mode)
xxx@192 ~ % java -showversion
java version "1.8.0_241"
Java(TM) SE Runtime Environment (build 1.8. 0 _241-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.241-b07, mixed mode)
Copy the code
X parameter
Non-standardized parameters, which may change from JVM version to JVM version.
For example, -xint: explain the execution. -xcomp: use the compiled code the first time. -xmixed: the JVM itself decides whether to compile the compiled code
Java code is interpreted, but is sometimes converted to native code for execution using jJIT just-in-time compilation technology. -xint means all interpreted execution. -xcomp means native code is compiled for the first use. The JVM itself decides when to compile native code.
XX parameters
Non-standardized parameters, mainly used for JVM tuning and debugging
- Boolean type
Format: -xx :[+-] Indicates whether to enable or disable the name attribute
Such as:
-XX:+UseConcMarkSeepGC -XX:+UseG1GC
- The key – value types
Format: -xx := Indicates the value of the name attribute. For example, -xx :MaxGCPauseMillis=500 -xx :GCTimeRatio=19
-xmx-xms-xms is equivalent to -xx :InitialHeapSize The size of the initial heap. -xmx is equivalent to -xx :MaxHeadpSize The size of the maximum heap
JVM toolkit use
jstat
View vm statistics
Address: document docs.oracle.com/javase/8/do…
Jstat can dynamically view classloading information, garbage collection information, and JIT compilation information
- Usage:
Usage: jstat -help|-options
jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]
Definitions:
<option> An option reported by the -options option
<vmid> Virtual Machine Identifier. A vmid takes the following form:
<lvmid>[@<hostname>[:<port>]]
Where <lvmid> is the local vm identifier for the target
Java virtual machine, typically a process id; <hostname> is
the name of the host running the target Java virtual machine;
and <port> is the port number for the rmiregistry on the
target host. See the jvmstat documentation for a more complete
description of the Virtual Machine Identifier.
<lines> Number of samples between header lines.
<interval> Sampling interval. The following forms are allowed:
<n>["ms"|"s"]
Where <n> is an integer and the suffix specifies the units as
milliseconds("ms") or seconds("s"). The default units are "ms".
<count> Number of samples to take before terminating.
-J<flag> Pass <flag> directly to the runtime system.
Copy the code
options | instructions |
---|---|
-class | Information about class clip loading |
-compiler | JIT compilation information |
-gc | Garbage collection information |
View class loading information
jstat -class10365, 1000, 10Loaded Bytes Unloaded Bytes Time3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55 3517 6738.4 0 0.0 3.55Copy the code
- Parameter Description:
10365 is the process number
1000 and 10 are printed at an interval of 1000 milliseconds, respectively, for a total of 10 times. If the current class loading information is not written, it is printed
- Output description:
Loaded: The number of Unloaded classes Bytes: the number of Bytes Unloaded Classes Time: the Time taken for the loading and unloading of the class
Viewing GC Information
jstat -gc 10365
S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT
10752.0 10752.0 0.0 4340.5 65536.0 23922.5 175104.0 144.0 17152.0 16426.6 2048.0 1907.5 1 0.004 0 0.000 0.004
Copy the code
- Parameter Description:
parameter | instructions |
---|---|
SOC, S1C, S0U, S1U | Total amount and usage of S0 and S1 |
EC, EU | Total amount and usage in Eden District |
OC, OU | Total amount and usage of Old area |
MC, MU | Total amount and usage of Metaspace |
CCSC, CCSU | Compress the amount and usage of class space |
YGC, YGCT | YoungGC number and time |
GGC, FGCT | The frequency and time of FullGC |
GCT | Total GC time |
Java8 memory structure division
Java heap area is mainly divided into the new generation and the old generation, and the new generation is divided into Eden area, S0 area and S1 area. Only one of S0 and S1 area is used at the same time.
The non-heap area is the operating system’s local memory, separate from the JVM heap area. Called Metaspace, the enabled object “short pointer” will have “CCS”, “CodeCache” stored JIT code information and JNI code information. If JIT compilation is not enabled, this memory will not exist.
View JIT compilation information
jstat -compiler 10365
Compiled Failed Invalid Time FailedType FailedMethod
1299 0 0 1.89 0
Copy the code
- Parameters that
parameter | instructions |
---|---|
Compiled | Number of compilation tasks executed |
Failed | Number of failed compilation tasks |
Invalid | Number of invalid compilation tasks |
Time | The time taken to perform the compilation task |
FailedType | The type of compilation that failed last time |
FailedMethod | The name and method of the class that failed the last compilation |
jmap
Here is the reference: www.jianshu.com/p/7abbb6ef7…
A heap dump generation tool that can be used to analyze the heap footprint of a JVM process, as well as an overview of the usage of all objects
Usage:
jmap [option] <pid>
(to connect to running process)
jmap [option] <executable <core>
(to connect to a core file)
jmap [option] [server_id@]<remote server IP or hostname>
(to connect to remote debug server)
where <option> is one of:
<none> to print same info as Solaris pmap
-heap to print java heap summary
-histo[:live] to print histogram of java object heap; if the "live"
suboption is specified, only count live objects
-clstats to print class loader statistics
-finalizerinfo to print information on objects awaiting finalization
-dump: <dump-options> to dump java heap in hprof binary format
dump-options:
live dump only live objects; if not specified,
all objects in the heap are dumped.
format=b binary format
file=<file> dump heap to <file>
Example: jmap -dump:live,format=b,file=heap.bin <pid>
-F force. Use with -dump:<dump-options> <pid> or -histo
to force a heap dump or histogram when <pid> does not
respond. The "live" suboption is not supported
in this mode.
-h | -help to print this help message
-J<flag> to pass <flag> directly to the runtime system
Copy the code
-heap Displays the heap configuration and usage
[root@localhost ~]# jmap -heap 18342
Attaching to process ID 18342, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.191-b12
using thread-local object allocation.
Mark Sweep Compact GC
Heap Configuration:
MinHeapFreeRatio = 40
MaxHeapFreeRatio = 70
MaxHeapSize = 33554432 (32.0MB)
NewSize = 11141120 (10.625MB)
MaxNewSize = 11141120 (10.625MB)
OldSize = 22413312 (21.375MB)
NewRatio = 2
SurvivorRatio = 8
MetaspaceSize = 21807104 (20.796875MB)
CompressedClassSpaceSize = 1073741824 (1024.0MB)
MaxMetaspaceSize = 17592186044415 MB
G1HeapRegionSize = 0 (0.0MB)
Heap Usage:
New Generation (Eden + 1 Survivor Space):
capacity = 10027008 (9.5625MB)
used = 7103016 (6.773963928222656MB)
free = 2923992 (2.7885360717773438MB)
70.83883846507354% used
Eden Space:
capacity = 8912896 (8.5MB)
used = 6630128 (6.3229827880859375MB)
free = 2282768 (2.1770172119140625MB)
74.38803280101104% used
From Space:
capacity = 1114112 (1.0625MB)
used = 472888 (0.45098114013671875MB)
free = 641224 (0.6115188598632812MB)
42.44528377757353% used
To Space:
capacity = 1114112 (1.0625MB)
used = 0 (0.0MB)
free = 1114112 (1.0625MB)
0.0% used
tenured generation:
capacity = 22413312 (21.375MB)
used = 11167688 (10.650337219238281MB)
free = 11245624 (10.724662780761719MB)
49.82613903737207% used
12018 interned Strings occupying 1036416 bytes.
Copy the code
-histo Generates the instance statistics histogram of the class
[root@localhost ~]$ jmap -F -histo 18342 >1.txt
Iterating over heap. This may take a while. Heap traversal took11.946 seconds.
[root@localhost ~]$ head -30 1.txt
Attaching to process ID 18342, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.191-b12
Object Histogram:
num #instances #bytes Class description
--------------------------------------------------------------------------
1: 51188 6866416 char[]
2: 4422 1296216 byte[]
3: 7871 1191696 int[]
4: 43636 1047264 java.lang.String
5: 8724 767712 java.lang.reflect.Method
6: 6509 718600 java.lang.Class
7: 21673 693536 java.util.concurrent.ConcurrentHashMap$Node
8: 7179 380872 java.lang.Object[]
9: 12965 277928 java.lang.Class[]
10: 6719 268760 java.util.LinkedHashMap$Entry
11: 124 243456 java.util.concurrent.ConcurrentHashMap$Node[]
12: 2729 239560 java.util.HashMap$Node[]
13: 14238 227808 java.lang.Object
14: 6617 211744 java.util.HashMap$Node
15: 3098 173488 java.util.LinkedHashMap
16: 2404 153856 java.net.URL
17: 1025 123000 org.springframework.boot.loader.jar.JarEntry
18: 1631 117432 java.lang.reflect.Field
19: 2019 96912 org.springframework.util.ConcurrentReferenceHashMap$SoftEntryReference
20: 1064 85120 java.lang.reflect.Constructor
21: 1299 67176 java.lang.reflect.Method[]
22: 1120 62720 java.lang.invoke.MemberName
Copy the code
The printed result has the number of instances, total memory footprint, and fully qualified name of the class, sorted in descending order by memory footprint. If the -histo switch is followed by the :live switch, only live objects will be counted, meaning that a Full GC will be fired before the count.
Note that the target JVM is stop-the-world when iterating through the heap and generating the histogram, so be careful with programs on large heaps or in production environments. If the target JVM is not responding, the -f argument is enforced (as with jStack), and the :live switch is invalidated.
-dump Generates heap dump snapshot files
[root@localhost ~]$ jmap -dump:live,format=b,file=dump_18342.hprof 18342
Dumping heap to /root/dump_18342.hprof ...
Heap dump file created
Copy the code
The generated binary snapshot file can be viewed using tools such as JHAT, MAT, and VisualVM that analyze heap dump. For example, retained size can be used to see what objects refer to large objects. The :live switch and the -f parameter have the same functions as the -histo option, and the process of generating snapshot files is also stop-the-world.
– finalizerInfo Displays the number of objects waiting for Finalize
[root@localhost ~]$ jmap -finalizerinfo 18342
Attaching to process ID 18342, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.191-b12
Number of objects pending for finalization: 0
Copy the code
Jmap field memory overflow
- Construct a heap memory overflow
@RestController
public class MemoryController {
private List<User> userList;
@GetMapping("heap")
public Object heap(a){
userList = new LinkedList<>();
while (true){
userList.add(newUser()); }}}Copy the code
Specifies that the JVM startup parameters -xms and -mmx are both 32M
The console runs out of memory when the browser accesses it
Exception in thread "http-nio-8080-exec-1" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "http-nio-8080-exec-2" java.lang.OutOfMemoryError: GC overhead limit exceeded
Exception in thread "SpringContextShutdownHook" org.springframework.context.ApplicationContextException: Failed to unregister LiveBeansView MBean; nested exception is java.lang.OutOfMemoryError: GC overhead limit exceeded
at org.springframework.context.support.LiveBeansView.unregisterApplicationContext(LiveBeansView.java:103)
at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1008)
at org.springframework.context.support.AbstractApplicationContext$1.run(AbstractApplicationContext.java:948)
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded
Copy the code
Export the memory image file
- Configure JVM parameters to automatically export memory overflow
# open memory automatic export - XX: + HeapDumpOnOutOfMemoryError # designated export path - XX: + HeapDumpPath =. /Copy the code
- Manually export using the jmap command
[root@localhost ~]$ jmap -dump:live,format=b,file=dump_18342.hprof 18342
Dumping heap to /root/dump_18342.hprof ...
Heap dump file created
Copy the code
Import the JDK’s own JVisualVM
jstack
Jstack usage reference: www.jianshu.com/p/99562e939…
Combat deadloops and deadlocks
[root@localhost ~]$ jstack -help
Usage:
jstack [-l] <pid>
(to connect to running process)
jstack -F [-m] [-l] <pid>
(to connect to a hung process)
jstack [-m] [-l] <executable> <core>
(to connect to a core file)
jstack [-m] [-l] [server_id@]<remote server IP or hostname>
(to connect to a remote debug server)
Options:
-F to force a thread dump. Use when jstack <pid> does not respond (process is hung)
-m to print both java and native frames (mixed mode)
-l long listing. Prints additional information about locks
-h or -help to print this help message
Copy the code
Thread state transition diagram
Print thread snapshot
This is just part of it
[root@localhost ~]$ jstack 18809
2020-03-07 14:40:32
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.191-b12 mixed mode):
"Attach Listener" #27 daemon prio=9 os_prio=0 tid=0x00007f3c88001800 nid=0x49a8 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"DestroyJavaVM" #26 prio=5 os_prio=0 tid=0x00007f3cb4009800 nid=0x497a waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"http-nio-8080-Acceptor" #24 daemon prio=5 os_prio=0 tid=0x00007f3cb48cf000 nid=0x4993 runnable [0x00007f3ca09dd000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.ServerSocketChannelImpl.accept0(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:422)
at sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:250)
- locked <0x00000000fe2a87c8> (a java.lang.Object)
at org.apache.tomcat.util.net.NioEndpoint.serverSocketAccept(NioEndpoint.java:466)
at org.apache.tomcat.util.net.NioEndpoint.serverSocketAccept(NioEndpoint.java:72)
at org.apache.tomcat.util.net.Acceptor.run(Acceptor.java:95)
at java.lang.Thread.run(Thread.java:748)
"http-nio-8080-ClientPoller" #23 daemon prio=5 os_prio=0 tid=0x00007f3cb49c4000 nid=0x4992 runnable [0x00007f3ca0ade000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.EPollArrayWrapper.epollWait(Native Method)
at sun.nio.ch.EPollArrayWrapper.poll(EPollArrayWrapper.java:269)
at sun.nio.ch.EPollSelectorImpl.doSelect(EPollSelectorImpl.java:93)
at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:86)
- locked <0x00000000fe454e00> (a sun.nio.ch.Util$3)
- locked <0x00000000fe454df0> (a java.util.Collections$UnmodifiableSet)
- locked <0x00000000fe454cd8> (a sun.nio.ch.EPollSelectorImpl)
at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:97)
at org.apache.tomcat.util.net.NioEndpoint$Poller.run(NioEndpoint.java:709)
at java.lang.Thread.run(Thread.java:748)
Copy the code
Deadlock detection
Build a deadlock
public class DeadLockDemo {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) throws Exception {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (lock1) {
System.out.println("thread1 synchronized lock1");
synchronized (lock2) {
System.out.println("thread1 synchronized lock2"); }}}},"thread1").start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (lock2) {
System.out.println("thread2 synchronized lock2");
synchronized (lock1) {
System.out.println("thread2 synchronized lock1"); }}}},"thread2").start(); }}Copy the code
Deadlock occurs when the program stops printing after only part of the print:
thread1 synchronized lock1
thread1 synchronized lock2
thread1 synchronized lock1
thread2 synchronized lock2
Copy the code
When jStack is used to print thread snapshots, deadlock information is displayed
. JNI global references:320
Found one Java-level deadlock:
=============================
"thread2":
waiting to lock monitor 0x00007fbc37805968 (object 0x000000076acd1f90, a java.lang.Object),
which is held by "thread1"
"thread1":
waiting to lock monitor 0x00007fbc37806eb8 (object 0x000000076acd1fa0, a java.lang.Object),
which is held by "thread2"
Java stack information for the threads listed above:
===================================================
"thread2":
at org.yuwb.customer.controller.DeadLockDemo.lambda$main$1(DeadLockDemo.java:33)
- waiting to lock <0x000000076acd1f90> (a java.lang.Object)
- locked <0x000000076acd1fa0> (a java.lang.Object)
at org.yuwb.customer.controller.DeadLockDemo$$Lambda$2/1134517053.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
"thread1":
at org.yuwb.customer.controller.DeadLockDemo.lambda$main$0(DeadLockDemo.java:22)
- waiting to lock <0x000000076acd1fa0> (a java.lang.Object)
- locked <0x000000076acd1f90> (a java.lang.Object)
at org.yuwb.customer.controller.DeadLockDemo$$Lambda$1/1237514926.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
Found 1 deadlock.
Copy the code
Use JStack to diagnose high CPU usage
Build an endless loop
public class DeadLockDemo {
private static final Object lock = new Object();
static class InfiniteLoopRunnable implements Runnable {
@Override
public void run(a) {
synchronized (lock) {
long l = 0;
while (true) { l++; }}}}public static void main(String[] args) throws Exception {
new Thread(new InfiniteLoopRunnable(), "thread1").start();
new Thread(new InfiniteLoopRunnable(), "thread2").start(); }}Copy the code
Run the top command to view the process information
View all threads in the process to find the highest CPU usage thread
$ top -Hp 12251
Copy the code
Exporting a Thread Snapshot
jstack 12251> 12251.log
Copy the code
Export thread snapshots to a file using jStack. Since the thread ID is represented in hexadecimal, we need to convert the thread ID to hexadecimal and grep.
cat 12251.log | grep -C 10 `printf "%x" 12266`
Copy the code
Reference documentation
- Docs.oracle.com/javase/8/do…
- www.jianshu.com/p/7abbb6ef7…