Home  >  Article  >  Java  >  How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

php是最好的语言
php是最好的语言Original
2018-08-01 15:30:464651browse

Everyone who knows a little bit should know that Java is a language that is easy to get started but difficult to master. Because it has a lot of knowledge, mastering it all cannot be achieved overnight. This article What is discussed is the operating mechanism and operation process of Java programs. Everyone should be looking forward to it. Some of the articles are collected by me. The layout may be a bit messy. Please forgive me. I will continue to update more high-quality articles to share with you. I We will always uphold the purpose of helping others. apache php mysql

java has two core mechanisms: java virtual machine and garbage collection mechanism. At present, the main focus here is on jvm running java programs.

(1) How to run a java program in the terminal (I ran this under mac, the principle is the same under windows, more or less the same)

Do this Under the premise, jdk must have been installed and there are no problems.

First of all, if you want to run a java class, you should first have a java class

1. Create a folder named java, and create a file ending with .java under the folder (I It was edited with sublime, other editors are also acceptable), here is HelloWorld as an example

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

2. Compile the file through the command

192:libexec huayu$ javac /Users/huayu/Desktop/java/HelloWord.java

After executing the command You will find an extra file ending with .class in the java folder

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

3. Execute the compiled class file (note that it must be in the location where the class file is located) Go down and execute the command, otherwise it will report a class not found error), you will see the following output in the terminal

192:java huayu$ java HelloWord
HelloWord

to here, congratulations! You have compiled and run your first java program in the terminal.

Actually, the editor knows that the letters in the above example are wrong. Please pretend not to notice and let me go. Don’t complain about me, hehe

(II ) The operating principle of jvm

The purpose of the above examples is not to let us learn how to run java programs in the terminal, but to let everyone know what operations are performed in the above process.

The javac program is a Java compiler. It compiles the file HelloWorld.java into the HelloWorld.class file and sends it to the java virtual machine. The virtual machine executes the bytecode placed in the class file by the compiler.

(1) The principle mechanism of JVM loading class files

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

The loading of classes in JVM is done by the class loader (ClassLoader) and its subclasses Implemented, the class loader in Java is an important Java runtime system component that is responsible for finding and loading classes in class files at runtime.
Due to the cross-platform nature of Java, the compiled Java source program is not an executable program, but one or more class files. When a Java program needs to use a class, the JVM will ensure that the class has been loaded, connected (verified, prepared and parsed) and initialized.

Loading of a class refers to reading the data in the .class file of the class into the memory. Usually, a byte array is created to read into the .class file, and then a Class object corresponding to the loaded class is generated. After loading is complete, the Class object is not complete, so the class is not available yet. When the class is loaded, it enters the connection phase, which includes three steps: verification, preparation (allocating memory for static variables and setting default initial values) and parsing (replacing symbolic references with direct references). Finally, the JVM initializes the class, including: 1) If the class has a direct parent class and the class has not been initialized, then initialize the parent class first; 2) If there are initialization statements in the class, execute these initialization statements in sequence.

The loading of classes is completed by class loaders, which include: root loader (BootStrap), extension loader (Extension), system loader (System) and user-defined class loader ( subclass of java.lang.ClassLoader). Starting from Java 2 (JDK 1.2), the class loading process adopts the Father Delegation Mechanism (PDM). PDM better ensures the security of the Java platform. In this mechanism, the Bootstrap that comes with the JVM is the root loader, and other loaders have only one parent class loader. The loading of a class first requires the parent class loader to load, and only when the parent class loader is unable to do anything, its child class loader loads it by itself. The JVM does not provide a reference to Bootstrap to Java programs.

The following is a description of several class loaders:

Bootstrap: generally implemented in local code, responsible for loading the JVM basic core class library (rt.jar);
Extension: from The class library is loaded in the directory specified by the java.ext.dirs system property, and its parent loader is Bootstrap;

System: also called the application class loader, and its parent class is Extension. It is the most widely used class loader. It records classes from the directory specified by the environment variable classpath or the system property java.class.path, and is the default parent loader of user-defined loaders.

(2) How does Java achieve "compile once and run everywhere"?

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

A virtual machine can be understood as a CPU that uses bytecode as machine instructions.

There are different virtual machines for different running platforms.

The Java virtual machine mechanism shields the differences in underlying operating platforms and achieves "compile once, run anywhere".

(3) Garbage collection mechanism (GC)

What is GC? Why is there a GC?

GC means garbage collection, memory Processing is where programmers are prone to problems. Forgotten or wrong memory recycling can lead to instability or even crash of the program or system. The GC function provided by Java can automatically monitor whether the object exceeds the scope to achieve the purpose of automatic memory recycling. The Java language No explicit operation method is provided to release allocated memory. Java programmers don't have to worry about memory management because the garbage collector takes care of it automatically. To request garbage collection, you can call one of the following methods: System.gc() or Runtime.getRuntime().gc(), but the JVM can mask explicit garbage collection calls. Garbage collection can effectively prevent memory leaks and effectively use available memory. The garbage collector usually runs as a separate low-priority thread to clear and recycle objects in the memory heap that have died or have not been used for a long time under unpredictable circumstances. Programmers cannot call the garbage collector in real time. A certain object or all objects undergo garbage collection (programmers cannot accurately control the collection time. Calling System.gc() or Runtime.getRuntime().gc() is equivalent to notifying the GC to collect it. It’s just for a moment, it’s not certain when you’ll collect it.)

In the early days of Java, garbage collection was one of the biggest highlights of Java, because server-side programming needed to effectively prevent memory leaks. However, as time has passed, Java's garbage collection mechanism has become something that has been criticized. Mobile smart terminal users usually feel that the iOS system has a better user experience than the Android system. One of the deep-seated reasons lies in the unpredictability of garbage collection in the Android system.

Supplement: There are many garbage collection mechanisms, including: generational copy garbage collection, marked garbage collection, incremental garbage collection, etc. A standard Java process has both a stack and a heap. The stack stores primitive local variables, and the heap stores the objects to be created. The Java platform's basic algorithm for heap memory reclamation and reuse is called mark and sweep, but Java has improved it by using "generational garbage collection." This method divides the heap memory into different areas according to the life cycle of the Java object. During the garbage collection process, the object may be moved to different areas:

- Eden: This is the initial location of the object The area where the object was born, and for most objects, this is the only area where they

have ever existed.
- Survivor: Objects that survived the Garden of Eden will be moved here.
- Tenured: This is the home of surviving objects that are old enough. The young generation collection (Minor-GC) process will not touch this place. When the young generation collection cannot put the object into the lifelong care garden, a full collection (Major-GC) will be triggered, which may also involve compression to make enough space for large objects.

JVM parameters related to garbage collection:

  • -Xms / -Xmx — Initial size of the heap/Maximum size of the heap

  • -Xmn — The size of the young generation in the heap

  • -XX:-DisableExplicitGC — Let System.gc() not generate Any function
  • -XX: PrintGCDetails — Print the details of GC operations
  • -XX: PrintGCDateStamps — Print the details of GC operations Timestamp
  • -XX:NewSize / XX:MaxNewSize — Set the size of the new generation/maximum size of the new generation
  • -XX:NewRatio - You can set the ratio between the old generation and the new generation
  • -XX:PrintTenuringDistribution - Set the age distribution of the objects in the survivor paradise after each new generation GC.
  • ##Bu


  • -XX:InitialTenuringThreshold / -XX:MaxTenuringThreshold: Set the initial value and maximum value of the old generation threshold

  • Big value


  • ##-XX: TargetSurvivorRatio: Set the target usage rate of the survivor area
  • Digression, talking about the operation of jvm Mechanism, then is Java a compiled language or an interpreted language?

  • I have checked a lot of information, and there are all kinds of information. Some people say it is an interpreted language, and some people say that it is a compiled language in order to compare java with js. language.

First of all, let’s take a look at the introduction of these two language types:

There are two main types of computer high-level languages: compiled and interpreted:

Compiled language: Before the program is run, there is a separate compilation process that translates the program into machine language. When the program is executed later, there is no need to translate it again.

Interpreted language: The program is translated into machine language when running, so the running speed is slower than compiled language.

The biggest difference between the two is whether to save the target machine code: compilation will translate the input source program into a target machine code in a certain unit (such as basic block/function/method/trace, etc.) and save it. (Whether it is on disk or in memory) subsequent execution can be reused; interpretation is to interpret and execute the instructions in the source program one by one, and execute them while interpreting. The target code is not saved, and there is no information that can be reused in subsequent executions.

Understand the running process of Java: Java source file (*.java) is compiled by the java compiler (javac) to generate a ByteCode bytecode file (*.class). The bytecode is designed by Java itself. A computer (i.e. Java virtual machine, JVM) interprets and executes. The virtual machine sends each bytecode to be executed to the interpreter. The interpreter translates it into the target machine code on a specific machine, and then runs it on the specific machine. .

How to run a java program in the terminal? Analyze its operating mechanism and its operating principles

Although the first process of Java is javac compilation, and its target file is ByteCode, not machine language, there may be three subsequent processing methods (here, currently for These three processing methods are not evaluated and need to be verified after in-depth discussion of JVM knowledge):

1. During runtime, ByteCode is sent to the interpreter one by one by the JVM, and the interpreter will translate it into machine code and run it. . (Many people say that this is the starting point for interpreted languages)

2. During runtime, some ByteCode may be compiled into target machine code by the just-in-time compiler (Just In Time Compiler, JIT) and then executed ( With method as the translation unit, it will be saved, and there will be no need to translate it into machine code for the second execution), because some JVMs are implemented using pure JIT compilation and do not have an interpreter inside them, such as JRockit and Maxine. VM.

3. RTSJ, after javac, performs AOT secondary compilation to generate static target platform code.

Sometimes, the above three methods may be used at the same time. At least, 1 and 2 are used at the same time, and 3 needs to be specified manually by the programmer.

In this regard, I am more willing to accept java as a hybrid language between compilation and interpretation.

end:

This article ends here. Thank you all for your support. If there are any deficiencies, please point them out and communicate. !

Related articles:

Analysis of program operation mechanism and errors in Java

In-depth interpretation of PHP operation mechanism

Related videos:

Method calling, definition and calling of void type method - JAVA beginner video tutorial

The above is the detailed content of How to run a java program in the terminal? Analyze its operating mechanism and its operating principles. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn