Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the secret of the java command?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the secret of the java command? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

To sum up: a simple java startup command, originally hidden so many secrets, this article reveals for you.

1 introduction

Students who have just started to learn java will not forget that after installing jdk, they will use the java-version command to check whether the installation is successful or not. Are there any other parameters that can be used? When developing and running java applications, you often see some-D parameters (for example, when using maven, package will use-Dmaven.test.skip). What are these parameters used for? And often when it comes to tuning, it involves the settings of-Xms and-Xmx. What does it mean? These are basically the parameters used when using the java command to start the application, and there are many parameters, especially when it comes to application tuning and problem diagnosis. Students who learn java should know about it. In this paper, the startup parameters of java command are described in detail, focusing on the commonly used settings and settings for debugging and monitoring.

2 java App launch

The java application is started using the java (class file) or java-jar (jar or war package) command. The java command actually generates an instance of JVM, and the java application runs in this JVM instance. JVM is responsible for class loading, runtime stack allocation and other work. When the application exits, the JVM instance will also be closed. Launching multiple java applications also starts multiple JVM instances, which do not affect each other (but they all share the resources of the same system), which is the logic behind the use of one JDK to run multiple java applications. The parameters used to start the application with the java command are basically for JVM. The JVM instance runs a Java program by calling the main () method of an initial class, which will serve as the starting point for the program's initial thread, by which any other thread is started. There are two types of threads within JVM: daemon threads (such as garbage collection threads) and non-daemon threads (main method threads and user-created threads using Thread). When all non-daemon threads in the program terminate, the JVM instance automatically exits.

3 description of launch parameters of java application

What parameters can be used in the java command, and what are the functions of these parameters? simply use java or java-help or java -? without parameters, you can see how to use this command and the description of the parameters, as shown below:

Java executes class files, and java-jar executes jar or war files. The above is only a brief list of the parameters. For more detailed description of the parameters, please refer to the java command description (https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html) on the official website. The parameters used to start the application with the java command are basically for JVM, which is also called the JVM parameter to some extent. Generally speaking, java startup parameters are divided into three categories, which are:

Standard parameter (-): a relatively stable parameter, available for each version of JVM.

Non-standard X parameters (- X): the default jvm implements the functionality of these parameters, but there is no guarantee that all jvm implementations are met and backward compatibility is not guaranteed.

XX parameter (- XX): this type of parameter varies from jvm implementation to jvm implementation and may be cancelled at any time in the future.

These parameters are described below.

3.1 Standard parameters (-)

Use java -? from the front. As you can see, the parameters starting with-belong to the standard parameters, and the commonly used-help,-version,-classpath,-Dproperty=value and so on belong to the standard parameters. The parameters are described as follows:

-D32 and-D64 indicate that the application runs in a 32-bit or 64-bit environment, respectively. The default mode that uses Java HotSpot Server VM is server mode, while the default mode of server mode is-D64, so when this parameter is not used, the default is-D64. -server selects "server" VM, and the default VM is server, which means it is running on a server-like computer. -cp or-classpath linux use ":", windows use ";" to separate directories, JAR files and ZIP file lists, used to search for class files. After using-classpath, jvm will no longer use the class search path in CLASSPATH. If both-classpath and CLASSPATH are not set, jvm uses the current path (.) As a class search path. -D = set system properties, and applications running on this jvm can use System.getProperty ("property") to get the value of value. If there are spaces in the value, you need to enclose the value in double quotes, such as-Dfoo= "foo bar". This parameter is typically used to set the system-level global variable value, such as the configuration file path, so that the property is accessible anywhere in the program. -verbose: [class | gc | jni] enable detailed output. Generally, when debugging and diagnosing, you will output the details of gc-version output the product version and exit-version: you need the specified version to run-showversion output product version and continue, that is, after the output version, continue to execute by java. This is different from-version-jre-restrict-search |-no-jre-restrict-search includes / excludes user-specific JRE-?-help output this help message-X output help for non-standard options-ea or-enableassertions [:. |:] enable assertions at the specified granularity Default jvm disable assertion mechanism-da or-disableassertions [:... |:] disable assertions with specified granularity-esa |-enablesystemassertions enable system assertions-dsa |-disablesystemassertions disable system assertions-agentlib: [=] load native proxy libraries For example-agentlib:hprof, see also-agentlib:jdwp=help and-agentlib:hprof=help-agentpath: [=] load native agent library by full pathname-javaagent: [=] load Java programming language agent, see java.lang.instrument-splash: display startup screen using specified image Generally used for graphic programming.

From the above description, we can know what our commonly used-version,-classpath,-Dproperty=value is for. In particular,-classpath (previously encountered running problems due to this), when jvm loads classes, the search path is this path, and it uses different delimiters in linux and windows. Linux is separated by:, windows;.

3.2 non-standard X parameter (- X)

Use the command java-X to output non-standard parameters. In normal use, we often use-Xloggc,-Xms,-Xmx,-Xss,-Xmn, as shown below:

-Xmixed defaults to mixed, and uses them to set the native code compilation mode of JVM-Xint means interpretive execution, all bytecode will be executed directly, and no cost code will be compiled-Xcomp means to compile to native code the first time it is used. -Xbatch forbids background code compilation, forces it to be compiled in the foreground, and the code can be executed only after compilation is completed. By default, jvm is compiled in the background. If the compilation is not completed, the foreground runs the code in interpretation mode-Xbootclasspath: sets the search path to guide classes and resources, allowing jvm to load bootclass from the specified path (which can be a semicolon-separated directory, jar, or zip) Rt.jar-Xbootclasspath/a to replace jdk: append to the end of the boot classpath-Xbootclasspath/p: before the bootstrap classpath, let jvm take precedence over the bootstrap default path to load all files in the specified path-Xcheck:jni appends check to the JNI function At this point, jvm passes the verification to the validity of the parameter of the JNI function. When illegal data is encountered in the local code, jmv will report a fatal error and terminate. The use of this parameter will cause performance degradation. Please use it with caution. -Xfuture lets jvm perform strict format checking on class files (the default jvm does not do strict format checking) to comply with the class file format specification. It is recommended that developers use this parameter-Xincgc to turn on incremental gc (off by default). This helps to reduce the pause of the application during a long GC. However, because it may be executed concurrently with the application, it will reduce the processing power of the CPU to the application-Xloggc:file is similar to-verbose:gc, except that the relevant information about each GC event is recorded in a file, preferably locally, to avoid potential network problems. If it appears on the command line at the same time as the verbose command,-Xloggc shall prevail. -Xms specifies the initial size of the jvm heap, which defaults to 1x64 of physical memory, with a minimum of 1m. You can specify units, such as k and m, and default to bytes if not specified. -Xmx specifies the maximum value of the jvm heap, which defaults to 1x4 or 1G of physical memory, and the minimum is 2m; the unit is the same as-Xms. -Xss sets the size of a single thread stack, which generally defaults to 512k. The initial and maximum values of the younger generation of the Xmn setting heap (heap) are the same as those of the-Xms. The younger generation is the address where new objects are stored, and GC occurs most frequently. If the setting is too small, it will easily trigger the younger generation garbage collection (minor gc). If the setting is too large, only full gc will take a long time. Oracle recommends setting the younger generation at one-fourth to half of the heap size. This command sets both the initial and maximum values, which can be set using-XX:NewSize and-XX:MaxNewSiz, respectively. -XshowSettings displays all settings and continues

Among the above parameters,-Xms,-Xmx,-Xss,-Xmn is a very important parameter in our performance optimization, and-Xloggc is a good debugger without professional tracking tools.

3.3The XX parameter (- XX)

Such parameters are very rich, including advanced runtime parameters, advanced JIT compilation parameters, advanced maintenance parameters and advanced GC parameters. You can see all of its parameters (https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html) on the official website. Different versions of jvm implementation may vary. According to the setting format, it is mainly divided into two categories, one is the boolean type, which is mainly used for the function switch, the other is the key-value type, the main performance, debugging parameters and other settings, some of the main parameters are listed below.

3.3.1 boolean type

This type of parameter, in the format-XX: [+ -], is used as a function switch to enable or disable attributes. Here are some of the following:

-final value of the XX:+PrintFlagsFinal output parameter-default value of the XX:+PrintFlagsInitial output parameter-XX:-DisableExplicitGC forbids calling System.gc () But jvm's gc is still valid-XX:+MaxFDLimit maximizes the number of file descriptors limit-XX:+ScavengeBeforeFullGC new generation GC takes precedence over FullGC execution-XX:+UseGCOverheadLimit limits the proportion of time spent on GC by jvm before throwing OOM-XX:-UseConcMarkSweepGC uses concurrent tag exchange algorithm for GC-XX:-UseParallelGC to enable parallel GC-XX:-UseParallelOldGC to enable parallelism for FullGC This item is automatically enabled when-XX:-UseParallelGC is enabled-XX:-UseSerialGC enables serial GC-XX:+UseThreadPriorities enables local thread priority-XX:-UseG1GC enables the GC3.3.2 key-value type of G1

For this type of parameter, the format:-XX:= indicates that the value of the attribute name is value. It is often used in performance tuning and debugging monitoring.

Performance tuning

When tuning performance, it is mainly to tune the memory allocation of JVM, including heap size, young generation size, young and old generation ratio, and so on.

-XX:LargePageSizeInBytes=4m sets large page size for Java heap-maximum percentage of free memory in java heap after XX:MaxHeapFreeRatio=70 GC-maximum memory occupied by newly generated XX:MaxNewSize=size objects-maximum memory occupied by XX:MaxPermSize=64m older objects-minimum percentage of free memory in java heap after XX:MinHeapFreeRatio=40 GC-ratio of XX:NewRatio=2 new generation memory capacity to old generation memory capacity-XX:NewSize=2.125m freshmen Default value of memory occupied when generation of substitute objects-XX:ReservedCodeCacheSize=32m retains the amount of memory occupied by code-XX:ThreadStackSize=512 sets the thread stack size If 0, use the system default value-XX:+UseLargePages uses large page memory

Debugging and monitoring

When it is necessary to monitor the application, especially to observe the situation of GC, check for problems after OOM, etc.

-XX:-CITime print time consumed in JIT compilation-XX:ErrorFile=./hs_err_pid.log saves error log or data to file-XX:-ExtendedDTraceProbes turns on solaris-specific dtrace probe-XX:HeapDumpPath=./java_pid.hprof specifies the path or file name when exporting heap information-XX:-HeapDumpOnOutOfMemoryError exports relevant information in the heap when it encounters OOM for the first time-XX:OnError= " "run the custom command-XX:OnOutOfMemoryError= after the fatal ERROR occurs" "execute a custom command when you encounter OOM for the first time-XX:-PrintClassHistogram prints the column information of the class instance when it encounters Ctrl-Break, which has the same function as jmap-histo-XX:-PrintConcurrentLocks prints information about concurrent locks when it encounters Ctrl-Break. Same as jstack-l function-XX:-PrintCommandLineFlags prints tags that appear on the command line-XX:-PrintCompilation prints relevant information when a method is compiled-XX:-PrintGC prints relevant information every time GC-XX:-PrintGC Details prints details every time GC-XX:-PrintGCTimeStamps prints time stamp of each GC-loading information of XX:-TraceClassLoading trace class-XX:-TraceClassLoadingPreorder trace Load information for all referenced classes-XX:-TraceClassResolution trace constant pool-unload information for XX:-TraceClassUnloading trace classes-information about XX:-TraceLoaderConstraints tracking class loader constraints 4 commonly used java application startup parameters

After the introduction of the previous chapters, you should have some understanding of the startup parameters (JVM parameters) of java, but there are too many parameters to remember all the parameters. If necessary, you are advised to check-help or see the official website instructions. Most of the time, we only need to remember a few commonly used ones. Let's summarize the commonly used JVM parameters.

4.1 Common standard parameters

-version, scenario: want to view the JDK version, java-version.

-dashed, scenario: maven skips unit tests and uses java-Dmaven.test.skip=true

-cp or-classpath, scenario: set the location of the jar package to be loaded, and use java-cp lib/test.jar com.test.TestMain

-verbose:gc, scene: output GC details

4.2 Common X parameters

-Xms and-Xmx, scenario: oom occurs due to insufficient memory, so adjust the heap size. If set to 1G, you can java-Xms1024m-Xmx1024m, usually to avoid frequent occurrence of GC,-Xms and-Xmx set to the same.

-Xss, scenario: there are many thread operands and local variables. Adjust the size of the thread stack to java-Xss1024k.

-Xmn, scene: the size of the younger generation is set to 512m, and you can java-Xmn512m.

-Xloggc:file, scenario: record the relevant information of each GC event in a file for subsequent analysis. You can java-Xloggc:logs/gc.log

4.3Common XX parameters

Print GC-related content, including heap situation, GC details, GC time, snapshot generated when OOM occurs, error log is recorded, etc., as follows:

-XX:+PrintHeapAtGC

-XX:+PrintGCDetails

-XX:+PrintGCDateStamps

-XX:+PrintGCTimeStamps

-XX:+PrintTenuringDistribution

-XX:+PrintGCApplicationStoppedTime

-XX:+HeapDumpOnOutOfMemoryError

-XX:HeapDumpPath=logs/heapdump.hprof. When OOM occurs, dump takes a snapshot to the file heapdump.hprof.

-XX:ErrorFile=logs/java_error_%p.log, when a JVM error occurs, output the log to java_error_%p.log.

The above parameters are highly used parameters. When using the java command to start the application, you can add these parameters to facilitate subsequent tuning and problem diagnosis.

5 Summary

Simple java startup commands are so complicated to use, of course, generally speaking, it will not be a big problem to use only java or java-jar to start the application by default. Understanding these parameters is undoubtedly a necessary skill for senior programmers when it comes to tuning, monitoring, and diagnosing. I hope that through this article, you can know the java commands and parameters.

This is the answer to the question about what is the secret of the java command. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report