Depurar aplicaciones Java desde la línea de comandos

Algunos errores son difíciles de reproducir en su computadora personal, pero son fáciles de reproducir en máquinas de producción o de prueba. Esta es una situación común a la que se enfrentan los desarrolladores profesionales de Java. Para depurar estos problemas, OpenJDK proporciona dos herramientas: remote debugging



 y  jdb



. Este artículo trata sobre jdb



.





Para las aplicaciones Java, las máquinas de prueba y producción típicas son servidores Linux sin GUI, por lo que solo están disponibles las herramientas de línea de comandos. Y no podemos utilizar IDE profesionales como IntelliJ IDEA, Eclipse o Apache NetBeans IDE.





En tales escenarios, podemos usar jdb



jdb



es el depurador de línea de comandos incluido con OpenJDK.





Esta es una traducción de la guía para principiantes. Obviamente, todos los expertos lo saben y no deberían perder el tiempo leyéndolo.





Depurar Java con la utilidad "jdb"

jdb se encuentra en el directorio jdk / bin. Utiliza la interfaz de depuración de Java (JDI) para iniciar y conectarse a la JVM de destino. La interfaz de depuración de Java (JDI) proporciona una interfaz de lenguaje de programación Java para depurar aplicaciones en el lenguaje de programación Java. JDI es parte de la arquitectura del depurador de la plataforma Java .





En esta sección, veremos cómo conectar jdb a una aplicación Java y comenzar a depurar y monitorear.





Comando Jdb

Formato de comando Jdb:





jdb [options] [classname] [arguments]

options:    This represents the jdb command-line options (e.g. attach, launch).
classname:  This represents the name of the main class to debug.
arguments:  This represents the arguments that are passed to the main() method of the class.
      
      



Aplicación Java de muestra para depuración

Java , . «-g» (javac -g Test.java), , . .





public class Test
{
    public static void main(String[] args)
    {
        System.out.println("First Line of main function");
        System.out.println("Second Line of main function");
        System.out.println("Third Line of main function");

        int i=0;
        System.out.println("i: " + i);
        i = 2;
        System.out.println("i: " + i);

        while(true)
        {
        }
    }
}
      
      



jdb java-

- jdb. jdb, , :





jdb Test
      
      



, «Test» , IDE. jdb JVM .





jdb JVM. JVM :





java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 Test
      
      



jdb jvm, :





jdb -attach 5005
      
      



.









jdb Java- Test:





/jdk/bin/jdb Test 
Initializing jdb ...
>
      
      



5, «stop», :





> stop at Test:5
Deferring breakpoint Test:5.
It will be set after the class is loaded.
>
      
      



"run":





> run
run  Test
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Test:5

Breakpoint hit: "thread=main", Test.main(), line=5 bci=0
5           System.out.println("First Line of main function");
      
      



«step»:





main[1] step
> First Line of main function
Step completed: "thread=main", Test.main(), line=6 bci=8
6            System.out.println("Second Line of main function");
      
      



«step»:





main[1] step
> Second Line of main function
Step completed: "thread=main", Test.main(), line=7 bci=16
7            System.out.println("Third Line of main function");
      
      



i "print":





main[1] print i
i = 0
      
      



"locals":





main[1] locals
Method arguments:
args = instance of java.lang.String[0] (id=841)
Local variables:
i = 0
      
      



, "where":





main[1] where
[1] Test.main (Test.java:10)
      
      



, "threads":





main[1] threads
Group system:
(java.lang.ref.Reference$ReferenceHandler)804 Reference Handler running
(java.lang.ref.Finalizer$FinalizerThread)805 Finalizer cond. waiting
(java.lang.Thread)806 Signal Dispatcher running
(java.lang.Thread)803 Notification Thread running
Group main:
(java.lang.Thread)1 main running
Group InnocuousThreadGroup:
(jdk.internal.misc.InnocuousThread)807 Common-Cleaner cond. waiting
      
      



, cont



:





main[1] cont
> i: 0
i: 2
      
      



jdb "help":





connectors -- list available connectors and transports in this VM
run [class [args]] -- start execution of application's main class
threads [threadgroup] -- list threads
thread -- set default thread
suspend [thread id(s)] -- suspend threads (default: all)
resume [thread id(s)] -- resume threads (default: all)
where [ | all] -- dump a thread's stack
wherei [ | all]-- dump a thread's stack, with pc info
up [n frames] -- move up a thread's stack
down [n frames] -- move down a thread's stack
kill -- kill a thread with the given exception object
interrupt -- interrupt a thread
print -- print value of expression
dump -- print all object information
eval -- evaluate expression (same as print)
set = -- assign new value to field/variable/array element
locals -- print all local variables in current stack frame
classes -- list currently known classes
class -- show details of named class
methods -- list a class's methods
fields -- list a class's fields
threadgroups -- list threadgroups
threadgroup -- set current threadgroup
stop [go|thread] []
-- set a breakpoint
-- if no options are given, the current list of breakpoints is printed
-- if "go" is specified, immediately resume after stopping
-- if "thread" is specified, only suspend the thread we stop in
-- if neither "go" nor "thread" are specified, suspend all threads
-- if an integer is specified, only stop in the specified thread
-- "at" and "in" have the same meaning
-- can either be a line number or a method:
-- :
-- .[(argument_type,...)]
clear .[(argument_type,...)]
-- clear a breakpoint in a method
clear : -- clear a breakpoint at a line
clear -- list breakpoints
catch [uncaught|caught|all] |
-- break when specified exception occurs
ignore [uncaught|caught|all] |
-- cancel 'catch' for the specified exception
watch [access|all] .
-- watch access/modifications to a field
unwatch [access|all] .
-- discontinue watching access/modifications to a field
trace [go] methods [thread]
-- trace method entries and exits.
-- All threads are suspended unless 'go' is specified
trace [go] method exit | exits [thread]
-- trace the current method's exit, or all methods' exits
-- All threads are suspended unless 'go' is specified
untrace [methods] -- stop tracing method entrys and/or exits
step -- execute current line
step up -- execute until the current method returns to its caller
stepi -- execute current instruction
next -- step one line (step OVER calls)
cont -- continue execution from breakpoint
list [line number|method] -- print source code
use (or sourcepath) [source file path]
-- display or change the source path
exclude [, ... | "none"]
-- do not report step or method events for specified classes
classpath -- print classpath info from target VM
monitor -- execute command each time the program stops
monitor -- list monitors
unmonitor -- delete a monitor
read -- read and execute a command file
lock -- print lock info for an object
threadlocks [thread id] -- print lock info for a thread
pop -- pop the stack through and including the current frame
reenter -- same as pop, but current frame is reentered
redefine
-- redefine the code for a class
disablegc -- prevent garbage collection of an object
enablegc -- permit garbage collection of an object
!! -- repeat last command
-- repeat command n times
# -- discard (no-op)
help (or ?) -- list commands
dbgtrace [flag] -- same as dbgtrace command line option
version -- print version information
exit (or quit) -- exit debugger
: a full class name with package qualifiers
: a class name with a leading or trailing wildcard ('*')
: thread number as reported in the 'threads' command
: a Java(TM) Programming Language expression.
      
      



.





"jdb.ini" ".jdbrc" user.home user.dir.





jdb:





quit
      
      



OpenJDK  Java-. . jdb , , , IDE . Java.





Para ayudarte, el autor del artículo escribió el libro electrónico 5 pasos para los mejores trabajos de Java . ¡Puede descargar esta guía paso a paso gratis!








All Articles