Efficient development: IntelliJ IDEA every day, you know these tips Debug?

https://www.aneasystone.com/archives/2017/09/java-debugging.html

 

Learning Java debugging techniques

In the process of software development, debugging can be said to be an essential skill. Debugging the English word is debug, by definition, is the removal of bugmeaning. As the saying goes, it is to create a bug in the programming process, so the importance of debug, no doubt, if you can master the skills of debugging, it can quickly locate a code bug. You know, looking to understand the code is not necessarily written in a code that the code may not be able to write a good debugging the code, in order to be able to write bug-free code, we have to have some basic debugging techniques.

We must first of its profits. Whether your development tool is IntelliJ IDEA or Eclipse, debugger is standard. In the face of the program in question, rational use of debugger breakpoints and tracing techniques, you can quickly locate the cause of the problem. Although the rational use of online logs are also easily locate the problem, but not the log debugging tool, not in the development environment System.out.printlnas a means of debugging, the debugger built-in debugger to master skills is the right way.

First, the actual debugging techniques IDEA

If you are doing Java development, I believe you would not have heard IntelliJ IDEA , and most Java developers, I am also the beginning of time to develop with Eclipse, but since the change of IDEA, will no longer leave no open it, completely turned into a big fan of the IDEA (sorry, hit a wave of advertising ..). Have to say, JetBrains software company from the Czech Republic is really the conscience of enterprises, which are the product is fine, in addition to IDEA, there WebStorm, PhpStorm, PyCharm other styles are very similar, including some similar shortcuts debugging techniques are also common.

Open IDEA debug panel, shown below, can be roughly divided into five sections:

  • Single-step tracking
  • Breakpoint Management
  • Evaluate the expression
  • Stack and thread
  • Variable Watch

idea-debugging.png

1.1 Single-step tracking

Speaking of debugging, estimated that many people first reaction is a program step by step follow-up analysis, in fact, IDEA provides many shortcuts to help us track program, you can probably listed below a few tips:

  • Show Execution Point

Often you need to debug the code, the code analysis, sometimes after browsing several source files can not find where the current execution, many people may use Navigate Backto return, although it could go back, but it might take more than Back button once, relatively speaking, the use of this technique to quickly navigate to the current line of code debugger is doing to be more simple.

  • Step Over

This is the basic single-step commands, every line of code is executed, if there are ways that line of code will skip, it can be said to really step by step.

  • Step In / Force Step In

Step OverThe method skips the execution of the return value can be observed, which if desired into the method, the implementation details of the observation method, you need to use Step Incommands. In addition, the Step Incommand will skip the jdk that comes with a systematic approach, if you want to track the details of the implementation of a systematic approach, you need to use Force Step Inthe command. Method for the single-step system, which when ignored, can configure the IDEA key Settings - Stepping> -> Build, Execution, Deployment -> Debugger for configuration, as shown below.

idea-step-skip.png

  • Step Out

When using the Step Incommand inside track to a method of, if you find yourself do not want to tune this method, and this method can be directly executed, and stops at the next line position call the method, which is Step Outthe command.

  • Drop to Frame

This move can be said to be a big kill debugger. When single-step debugging, if due to carelessness lead to a single step too far, do not see the implementation of the critical code, such positioning would like at a certain value of the intermediate variable, this time if they can return to that line of critical code and then execute it again like, Drop to Frameit provides us the ability, it can be back to where method calls (with Step Outnot the same, Step Outis to return to the next line method call), so that we can once again this debugging method, this time not careless again .

Drop to frame The principle is very simple, as the name suggests, it will be the top of a stack stack frame deletion (that is, the method currently executing), let the program return to a stack frame (the parent method), you can imagine, this will only restore the stack local variables, global variables can not be restored, if there is local to the global variable operating method, there is no way to do it again in.

  • Run to Cursor / Force Run to Cursor

These two commands are useful when you need a temporary break, such as already know what they want to analyze the lines of code, but do not need many unnecessary breakpoints, you can perform a row to use this command directly, Force Run to Cursoror even ignore all off points directly to where we want to analyze.

Breakpoint Manager 1.2

A breakpoint is one of the basic functions of a debugger, you can let the program be suspended where needed, helping us to analyze the process of running the program. IDEA breakpoint management in the following figure, the rational use of breakpoints skills can quickly stop the program to where we want to stop:

idea-breakpoints.png

Breakpoints may be divided into two types: line breakpoint refers to a pause on a particular line of code, while the global breakpoint is satisfied when a condition to stop, a fixed stop is not limited to a line, such as Halt when an exception occurs.

1.2.1 Line Breakpoint

  • Suspend (All / Thread)
  • Condition

Conditional breakpoint. It should also use the debugger for each developer should master a skill, when faced with traversing large List or Map object, for example, there are 1000 Person object, you can not tune each object again, you might in just person.name = 'Zhangsan' so that when broken down breakpoints, conditional breakpoints can be used, as shown below:

idea-breakpoints-condition.png

  • Log message to console
  • Evaluate and log

When you see the top of Suspendthis option when some people may be surprised, my next break point is to let the program do not stop it? This option also need to do? Is not it redundant? Do you want the program to the next break point is not to stop? Found Evaluate and logbefore this technique, I also feel that this is very strange, until one day I suddenly found Suspend Off + Evaluate and log fit is really too useful. Front have said, do not put System.out.printlnas a debugging tool, because you can use this technique to print all the information you want to print, without the need to modify your source code.

  • Remove once hit

A one-time break. Described above Run to Cursoris an example of a one-time breakpoint.

  • Instance filters
  • Class filters
  • Pass count

I use these not many, but it should also be very useful tips can first down. In IDEA where each object has an instance ID, Instance filtersit is used when the code is located at the breakpoint setting examples and ID match is broken down. Pass countIt is time to pause in the implementation of the breakpoint to the first few times.

1.2.2 Global breakpoints

  • Exception breakpoints
  • Method breakpoints
  • Field watchpoints

Personally feel these skills are not very common, interested students own experiments a bar.

1.3 evaluate the expression

In the next step through a bunch of buttons, there is a discreet button that is "to evaluate the expression." It is useful when debugging, you can view the value of a variable, you can calculate the value of an expression, you can even calculate the value of their own piece of code, which correspond to the following two different modes:

  • Expression pattern (Expression Mode)
  • Fragment mode (Code Fragment Mode)

This model is similar to two Eclipse inside Expression View and Display View. In the Display View where you can also write a piece of code to execute, it is indeed very powerful, but note that only write code snippets here, you can not customize the method, as shown below:

idea-evaluate-code-fragment.png

1.4 Stack and thread

Say nothing of this, a view you can view all the current thread, the other view can view the current function stack. In view of the thread where you can be Thread dump, analyze each thread of what is currently being done; the stack view where you can switch stack frame, combined with variable viewing area on the right, you can easily view each function in the local variables and parameters.

  • Thread View
  • Stack view

idea-threads.png

1.5 Variable Watch

Variable region and the observation region may be combined, may be displayed separately (as shown below), I prefer separate display, such local variables, static variables and parameters displayed in the variable region, to be observed in the display observation expression Area. Expression mode is similar to the viewing area seeking value in the expression, you can add an expression of the need to observe, when debugging can see the value of the expression real-time. Contents of the variable region is relatively fixed, with the left adjustment stack frame, the value will become different. Here you can also modify the original value of the variable.

idea-variables.png

Second, the use jdb command line debugger

I believe many people have heard gdb, it can be said that the originator of debugging sector, previously when learning C / C ++, is to use it to debug the program. And gdb, like, jdb is a command-line version of the debugger for debugging Java programs. Jdb download and does not require installation, it comes with the JDK tools (in the JDK bin directory, JRE is not).

Each study new technology, I always see if there is a command-line version of the tool can replace, operate giving a sense of security at the command line, every instruction, every parameter, are crystal clear out there, which compared to the graphical tool, you can learn deeper knowledge, rather than the technical details hidden behind the graphical interface, you can find every command line parameters, each configuration, can be learned It points.

2.1 jdb basic commands

Java program debugging jdb shown below, using the direct jdb Testcommand to load the program.

jdb-debugging.png

Operation End jdb Testafter the command, then the program is not running, but stopped there waiting for further orders. Fortunately, this time we can think of where the next break point, such as at a breakpoint main () function, you then use the runcommand to run the program:

1
2
3
4
5
6
7
8
9
> stop in Test.main
正在延迟断点Test.main。
将在加载类后设置。
> run
运行Test
设置未捕获的 java.lang.Throwable
设置延迟的未捕获的 java.lang.Throwable
>
VM 已启动:设置延迟的断点:Test.main

As can be seen in the execution runbefore the command, the program has not yet begun to run, this time the breakpoint is called "deferred breakpoints", the time when the program is actually up and running, which is the start of the JVM, it will set a breakpoint. In addition to stop in Class.Methodthe command, you can also use stop at Class:LineNumberway to set a breakpoint.

1
main[1] stop at Test:25

Under breakpoints in jdb, the no IDEA in so many tricks, and what conditional breakpoints, what Instance filters are not supported, only obediently step by step. At the breakpoint, can listcommand to view the vicinity of the breakpoint code, or a stepsingle-step command, printor dumpprint the value of a variable or expression, localsa command to view all variables in the current method, contthe command code execution continues. There are other commands do not introduced, it can be used helpto view a list of all the commands, or reference jdb official documents .

2.2 explore the class file structure

When debugging a Java program in jdb, it is possible the source code files and class files are not together, this time you need to specify the source location:

1
# jdb -sourcepath path/to/source Test

If you do not specify a source location, using the listcommand will prompt can not find the source file, the source file if it does not, then that is completely blind in jdb in tune. We know that at the time of execution of Java code, in the form of byte code running on the JVM, you can guess, class file and is sure to have some information about the source associated with the similar obj file C / C ++ language is the same, Otherwise listhow the command can display the currently executing code which row it? We can use open source jclasslib software to view class content of the document, a standard class file contains the following information:

  • Basic Information
  • Constant pool
  • interface
  • Attributes
  • father
  • Field
  • method

    • Code properties

      • Property line number
      • Local variable table

As shown below, the most important part is the Code attribute, Code attribute has the following properties LineNumberTable line number, the debugger is used LineNumberTable key associated with the source code and the bytecode. About class file, you can refer to the article "in-depth understanding of the Java Virtual Machine," the study notes .

dis-class-file.png

Off-topic: How to debug when no source?

If there is no source code, although you can also use step by step through the jdb years, but there is no way to display the currently running code, which is simply a blind transfer. This time can only be used byte code debugging tools, and common byte-code debugger has: Bytecode Visualizer , JSwat Debugger , the Java Debugger the ByteCode (JBCD) , etc., refer here .

Third, on remote debugging

By learning jdb, we have more and more closer to the truth Java debugger, but short of the last step. Let's take a look at IDEA Java program in how to be debugged, if you have a strong curiosity, then the debugging of applications in IDEA there may have discovered the secret of the following:

idea-debug-java.png

Or when debugging tomcat, we had a similar string of curse as if the general parameters:

idea-debug-tomcat.png

This is like a string of curse following parameters like, once you understand the parameters of this series, you will break the curse Java debugger, and then to recognize the true face of Java Debugger:

1
2
"C:\Program Files\Java\jdk1.8.0_111\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:20060,suspend=y,server=n Foo
Connected to the target VM, address: '127.0.0.1:20060', transport: 'socket'

And there are two key points:

  1. With Java program at runtime -agentlibDLL file parameters, this parameter is used to indicate additional JVM is loaded at startup, -agentlibparameters and -javaagentnot the same, the library should be a program written by a native C / C ++ (JNI), similar to jdwp here, on Windows corresponds to a jdwp.dll library files, correspondence jdwp.so files on Linux. Then the jdwp libraries in the end is to do what? A string argument behind it is what does this mean?
  2. Parameters jdwp's seemingly referred to the socket, and has address = 127.0.0.1: 20060 This IP address and port number, and the following Connected to the target VM also seems to indicate that the debugger connected to such a network address, then the address in the end what is it then? Because this is a local debugging, so the IP address is 127.0.0.1, so if it is remote debugging, is not there also support it?

In the IDEA Run / Debug Configuration configuration page, you can also add a remote debugging interface as shown below, can be found in the above parameter string of curse has emerged:

idea-remote-debugging.png

Before we can start remote debugging, with these questions we may wish to learn the basic principles of Java debugger.

Four, Java debugging principles and JPDA Profile

In the world of martial arts, martial arts world can be divided into two types: one to pay attention to new moves, when can surprise moves, good use of the characteristics of the weapons and their own ingenious way Gongdi not prepared; pay attention to the other internal organs Heart, even the most common moves, combined with deep internal forces themselves, but also when there is Thunder trend moves. In fact, in the technology world, martial arts can also be divided into two types: techniques and principles. The above talked about so much, whether you have all the debugging techniques IDEA or just memorize all the command jdb or whatever, just change the moves, remain the same, we are going to look at commissioning internal organs Heart's.

4.1 JPDA

We know, Java programs are run on the JVM, we want to debug Java programs, you actually need to request the status of the current operating state of the JVM, JVM and issue certain instructions or accept a callback JVM. To debug Java programs, JVM and interfaces to provide a complete set of tools for debugging, this set of interfaces together we call it JPDA(Java Platform Debugger Architecture, Java platform debug architecture). This system provides an API set for debugging a Java program developers, it is a set of interfaces and protocols for developing Java debugging tools. In essence, it is our gateway to the virtual machine, visit a channel running state of the virtual machine, a set of tools.

JPDA consists of three relatively independent levels composed, and the provisions of the interaction between the three of them. These three levels from low to high, respectively, is a Java Virtual Machine Tool Interface (JVMTI), Java debug wire protocol (the JDWP) and Java Debug Interface (JDI), as shown below (image from the IBM the developerWorks ):

jpda.jpg

The three modules the debugging process into several natural concepts: debugger (Debugger) and the debuggee (debuggee), and among them communicator. Debugee we want to debug runs on the Java Virtual Machine, it can JVMTI this standard interface to monitor information on the current virtual machine; debugging to define the user debug interface that can be used, it can be debugged via these interfaces, users VM send debug command while the debugger to accept and display the debugging results. Between the debugger and the debugger, debug commands and debug the results are JDWP transmission protocol of the pass. After all the commands are encapsulated JDWP command packet, to be sent through the transport layer debuggee, the debuggee JDWP received command packet, parses the command and calls into JVMTI, operating on the debuggee. Similarly, the operating results of JVMTI, JDWP is formatted into packets and sent to the debugger returns to the calling JDI. The debugger developers is to get the data through JDI, issued a directive. Details, refer to a series of articles on developerWorks IBM "in-depth Java debugging system" .

4.2 Connectors & Transport

Here, we already know jdwp is a communication protocol between the debugger and the program being debugged. However, the command-line parameters -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:20060,suspend=y,server=njdwp seemingly in more than that. In fact, this place jdwp.dll library to JDI, JDWP, JVMTI three-part series into a whole, it can not only invoke the debugger's ability to provide local JVMTI, also achieved JDWP communication protocols to meet between the JVMTI and JDI communication. Want to fully understand the meaning of this string parameters, we also need to learn two concepts: Connectors (connector) and Transport (transport).

Common connector has the following five kinds, which refers to the JDWP establishing a connection:

  • Socket-attaching connector
  • Shared-memory attaching connector
  • Socket-listening connector
  • Shared-memory listening connector
  • Command-line launching connector

In which the difference between attaching connector and listening connector is that in the end the debugger as a server, or as a server program being debugged.
JDWP transmission refers to the means of communication, once established the connection between the debugger and the program being debugged, you need to start the communication between them, there are two kinds of communication: Socket (socket) and Shared-memory (shared memory, only on the Windows platform).

4.3 actual remote debugging

Through the above study we learned, Java debugger and the program being debugged is in the form of C / S structure to run, it must first have one end in the form of start up the server, and then another period of up to client connections. If the debugger is run at the server, you must add the following command line arguments (on jdwp parameters, refer to the document of JavaSE ):

1
2
# java -agentlib:jdwp=transport=dt_socket,server=y,address=5005 Test
# java -agentlib:jdwp=transport=dt_shmem,server=y,address=javadebug Test

The first is a socket communication system to start a program, the second sentence is shared memory, the way to start a program, the way to specify a socket port number, which is connected to the debugger through the port number, specify a shared memory connected name, rather than port number. After running the program, you may be used jdb the -attachparameters and to connect the debugger program to be debugged:

1
2
# jdb -attach 5005
# jdb -attach javadebug

On the Windows platform, the first command will be reported this error: java.io.IOException: shmemBase_attach failed The: at The System at The CAN not the Find File specified , this is due to the jdb -attachsystem's default transmissions to establish a connection, and in the Windows default transmission is shared memory . To be used on a Windows socket connection mode, use the jdb -connectcommand, but the command argument is not a good memory on the wording:

1
2
# jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=5005
# jdb -connect com.sun.jdi.SharedMemoryAttach:name=javadebug

If, in turn, want the debugger to run the server, execute the following command:

1
# jdb -listen javadebug

Then Java program to connect the debugger with the following parameters:

1
2
# java -agentlib:jdwp=transport=dt_shmem,address=javadebug, suspend=y Test
# java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:5005,suspend=y,server=n

Finally, we come back to take a look at this string of curse parameters IDEA print out, I can safely guess, IDEA when debugging, first start the debugger to the server form, and listening at port 20060, then Java socket communication program connected to the port, and the JVM pauses and waits for debugging.

1
2
"C:\Program Files\Java\jdk1.8.0_111\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:20060,suspend=y,server=n Foo
Connected to the target VM, address: '127.0.0.1:20060', transport: 'socket'

If the remote debugging under IDEA, you can refer to another article related to the subject of debugging on IBM developerWorks: using the Eclipse remote debugging Java applications .

to sum up

This article introduces some common debugging techniques IDEA, and debug Java programs by using jdb, learned jdb common commands, and finally leads to the topic of principle by the debugger remote debugging on the JPDA, JVMTI, JDWP, JDI, etc. With the concept of a preliminary understanding. From moves to the Heart, by the skill to principle, and gradually uncover the mystery of the Java debugger. For developers, if you only know the moves, only some of the odd kinky tricks, so he just put it handy tools more difficult to obtain a qualitative breakthrough in technology; and if only know how to Heart, only immersed in the basic principles and theories, then he can only do a academic attracted me, it takes full of useless but no big deal. We should internally and externally, the moves and miscellaneous combine mastery, in order to be immortal.

Finally, the last, on the topic of debugging I have to add that: Debugger is a time-consuming process that once required debugging to locate the problem, explain the logic and clarity of the code in question, the best code is not required for debugging. So, less debugging, unit testing a little more, a little more reconstruction, the code is written more clearly is the best way of programming.

Side story: uncertainty about the effect of the debugger

In quantum physics, there is a term called the uncertainty principle , also known as the uncertainty principle , talking about the position and the momentum of the particle can not be determined at the same time, the smaller the uncertainty of the position, the more uncertain the momentum large, and vice versa. Said the white point is, if you want to very accurately measure a particle's position, you can not accurately measure the momentum of the particle; if you want very accurate measurements of particle momentum, then the particle's position on uncertainty; precisely because the measurement itself, It will cause the affected system.

This phenomenon sets in the debugger field, has a similar effect. Due to interference debugger itself, the program has not before the procedure. So the question comes, the results of running out under the debugger, really credible? Here is an interesting example I want out, we suppose a breakpoint, the final output of the program will do what is in the fourth row?

debugger-reflactor.png

 

Guess you like

Origin www.cnblogs.com/xiang--liu/p/12583663.html