Location>code7788 >text

Getting to grips with JVM diagnostics and tool usage

Popularity:20 ℃/2024-08-01 10:23:40

JVM (Java Virtual Machine) is the basic environment for Java programs to run, it provides memory management, thread management and performance monitoring and other functions. Eat through the JVM diagnostic methods can help developers more effectively solve the problems encountered by Java applications at runtime. The following are some common JVM diagnostic methods:

  1. Using JConsole:

    • JConsole is a visual monitoring tool that allows you to connect to a local or remote instance of the JVM to view memory usage, thread status, class loading information, and more.
  2. Using VisualVM:

    • VisualVM provides richer features, including thread analysis, memory leak analysis, GC log analysis, and so on.
  3. Using jstack:

    • jstack is a command line tool that generates snapshots of Java threads for analyzing the state of threads and deadlock problems.
  4. Using jmap:

    • jmap can be used to generate a heap dump snapshot (heap dump), analyze memory usage and find memory leaks.
  5. Using jstat:

    • jstat provides performance data for running JVM instances, including class loading, memory, garbage collection and other statistics.
  6. Using jcmd:

    • jcmd is a multifunctional command line tool that can perform various diagnostic commands such as getting thread stack and memory information.
  7. Analyzing GC Logs:

    • Garbage collector (GC) logs contain detailed information about garbage collection, and by analyzing these logs you can understand GC behavior and performance bottlenecks.
  8. Using MAT (Memory Analyzer Tool):

    • MAT is a powerful heap dump analysis tool that helps developers analyze memory usage and find memory leaks.
  9. Using Profilers:

    • Using performance analysis tools (e.g. YourKit, JProfiler) can help developers understand the performance bottlenecks of an application.

Through these methods, you can gain a deeper understanding of the internal workings of the JVM mechanism , so as to more effectively diagnose and solve problems in Java applications. The following V brother one by one to explain the use of methods.

1. Use of JConsole

Simulating sample code to demonstrate the use of the JConsole tool, we can create a simple Java application that will demonstrate memory usage, thread monitoring, and GC activity. We will then use JConsole to monitor this application.

Sample Java Application Code

import ;
import ;

public class JConsoleDemo {
    private static final int LIST_SIZE = 1000;
    private static List<Object> list = new ArrayList<>();

    public static void main(String[] args) throws InterruptedException {
        // Simulating Memory Usage Growth
        for (int i = 0; i < 5; i++) {
            (new byte[1024 * 1024]); // increase1MBdigital
            (1000); // analog delay
            ("Memory used: " + (i + 1) + "MB");
        }

        // Simulate thread activity
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                ("Thread 1 is running");
                try {
                    (500);
                } catch (InterruptedException e) {
                    ().interrupt();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (true) {
                synchronized () {
                    ("Thread 2 is running");
                }
                try {
                    (500);
                } catch (InterruptedException e) {
                    ().interrupt();
                }
            }
        });

        ();
        ();

        // analog (device, as opposed digital)GCmaneuver
        ().gc();
    }
}

Monitoring the sample application using JConsole

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . JConsoleDemoRun the application.
  2. Start JConsole

    • At the command line, typejconsoleand enter.
  3. Connecting to the application

    • In JConsole, select Connect and then select the running JConsoleDemo application from the list.
  4. Monitoring Memory Usage

    • In the Memory tab, watch the heap memory change. You should see a gradual increase in memory usage as the program runs.
  5. Monitor thread status

    • Switch to the Threads tab to see the activity of the threads. Notice how Thread 1 and Thread 2 are running.
  6. Analyzing Thread Deadlocks

    • If thread 2 is waiting in a synchronization block while thread 1 tries to acquire the same lock, this will result in a deadlock. Use the "Find Deadlocked Threads" function to detect this.
  7. Monitoring GC Activity

    • Go back to the Memory tab to see GC statistics such as GC count and GC time.
  8. Generating Heap Dumps

    • If you need to further analyze memory usage, you can use the "Dump Heap" function in the "Memory" tab to generate a heap dump.
  9. Monitoring MBeans

    • If the application has registered custom MBeans, you can view them in the "MBeans" tab.

With this example, you can learn how to use JConsole to monitor memory usage, thread status, and GC activity of your Java application. This information is critical for diagnosing performance problems and optimizing your application.

2. Using VisualVM

VisualVM is a powerful all-in-one tool that provides in-depth analysis of a Java application, including CPU, memory, threads and GC. Below is a simple example of a Java application that will demonstrate how VisualVM can be used for monitoring and analysis.

Sample Java Application Code

public class VisualVMDemo {
    private static final int ARRAY_SIZE = 1000;
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        // Create a large array to simulate memory usage
        Object[] largeArray = new Object[ARRAY_SIZE];

        // Create threads to simulateCPUUsage and thread activity
        Thread cpuIntensiveThread = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                // analog (device, as opposed digital)CPUIntensive missions
                for (int j = 0; j < 100000; j++) {
                    // empty loop body (computing)
                }
            }
        });

        // Create threads to simulate线程死锁
        Thread thread1 = new Thread(() -> {
            synchronized (lock) {
                ("Thread 1 acquired lock");
                try {
                    (500);
                } catch (InterruptedException e) {
                    ().interrupt();
                }
                synchronized () {
                    ("Thread 1 acquired second lock");
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized () {
                ("Thread 2 acquired second lock");
                try {
                    (500);
                } catch (InterruptedException e) {
                    ().interrupt();
                }
                synchronized (lock) {
                    ("Thread 2 acquired lock");
                }
            }
        });

        // Starting a thread
        ();
        ();
        ();

        // analog (device, as opposed digital)内存泄漏
        while (true) {
            // Continuously creating objects without releasing references
            largeArray[(int) (() * ARRAY_SIZE)] = new Object();
            (10);
        }
    }
}

Monitoring Sample Applications with VisualVM

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . VisualVMDemoRun the application.
  2. Start VisualVM

    • At the command line, typevisualvmand enter.
  3. Connecting to the application

    • VisualVM automatically detects running Java applications. If it is not automatically detected, you can add it manually using the "Add JMX Connection".
  4. Monitor CPU usage

    • In the Monitor tab, view the "Current" and "Historical" CPU usage.
  5. Monitoring Memory Usage

    • In the Monitor tab, view heap and non-heap memory usage.
  6. Analyzing Memory Leaks

    • Use the "Memory" tab and click the "GC" button to trigger garbage collection, then watch for objects that are not being collected, which may indicate a memory leak.
  7. Analyzing Thread Deadlocks

    • In the Threads tab, look for deadlocked threads. visualVM displays the deadlocked threads and their call stacks.
  8. Analyzing GC activities

    • In the Monitor tab, view GC statistics, such as the number of GCs, GC duration, and so on.
  9. Generating Heap Dumps

    • In the Memory tab, click the Heap Dump button to generate a heap dump file, which can then be further analyzed using the Analysis tool.
  10. Analyze Sampling CPU Profile

    • In the CPU tab, launch the CPU Analyzer to see which methods are taking up the most CPU time.
  11. View class loading information for your application

    • In the Classes tab, view the loaded classes and when they were loaded.

With this example, you can learn about the many features of VisualVM, including CPU analysis, memory analysis, thread analysis, and GC analysis. These tools can help you diagnose and optimize the performance problems of your Java applications.

3. Using jstack

jstackis a command line tool that is used to generate a stack trace of a Java thread, which is useful for analyzing thread state and deadlock problems. The following is a simple sample Java application that demonstrates how to use thejstackto get a stack trace of the thread.

Sample Java Application Code

public class JStackDemo {
    public static void main(String[] args) {
        // Create a sample object,Used to identify in the stack trace
        Object exampleObject = new Object();

        // Create two threads,They will try to acquire the same lock,cause a deadlock
        Thread thread1 = new Thread(new DeadlockDemo("Thread-1", exampleObject, true));
        Thread thread2 = new Thread(new DeadlockDemo("Thread-2", exampleObject, false));

        ();
        ();
    }
}

class DeadlockDemo implements Runnable {
    private final String name;
    private final Object lock1;
    private final boolean lockOrder;

    public DeadlockDemo(String name, Object lock1, boolean lockOrder) {
         = name;
        this.lock1 = lock1;
         = lockOrder;
    }

    @Override
    public void run() {
        (name + " started");

        if (lockOrder) {
            synchronized (lock1) {
                (name + " acquired lock1");
                try {
                    (500); // simulation work
                } catch (InterruptedException e) {
                    ().interrupt();
                }
                synchronized () {
                    (name + " acquired lock2");
                }
            }
        } else {
            synchronized () {
                (name + " acquired lock2");
                try {
                    (500); // simulation work
                } catch (InterruptedException e) {
                    ().interrupt();
                }
                synchronized (lock1) {
                    (name + " acquired lock1");
                }
            }
        }
    }
}

utilizationjstackGetting the thread stack trace

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . JStackDemoRun the application.
  2. Get Java Process ID

    • On the command line, use thejpscommand to view all Java processes and their PIDs.
  3. utilizationjstackGetting the stack trace

    • Assuming that the PID of your Java application is 1234, use the following command to get a thread stack trace:
jstack 1234
     
  1. analysis output

    • jstackcommand will output a stack trace of all threads. You can view the state of each thread and the methods they called.
  2. Finding Deadlocks

    • In the output, thejstackwill specifically mark deadlocked threads and show deadlock loops. Example:
    Found one Java-level deadlock:
    ===================
    "Thread-1":
        at JStackDemo$(:23)
        - waiting to lock monitor 0x00000007f7e8b8400 (object 0x00000007f7e8b8420, a )
        - locked ownable synchronizer 0x00000007f7e8b8420 (a $NonfairSync)
    "Thread-2":
        at JStackDemo$(:23)
        - waiting to lock monitor 0x00000007f7e8b8420 (object 0x00000007f7e8b8420, a )
        - locked ownable synchronizer 0x00000007f7e8b8400 (a $NonfairSync)
    Java stack information for the threads listed above:
    ===================================================
    "Thread-1":
            at JStackDemo$(:23)
            - waiting to lock <0x00000007f7e8b8400>
            - locked <0x00000007f7e8b8420>
    "Thread-2":
            at JStackDemo$(:23)
            - waiting to lock <0x00000007f7e8b8420>
            - locked <0x00000007f7e8b8400>
  1. Resolving Deadlocks
    • according tojstackoutput, you can analyze the cause of the deadlock and modify the code to avoid it, for example by ensuring that all threads acquire locks in the same order.

With this example, you can see thatjstackis a powerful tool to help you quickly diagnose threading problems and deadlocks.

4. Using jmap

jmapis a command line utility for generating a Java heap dump snapshot or connecting to a running Java Virtual Machine (JVM) and retrieving useful information about the heap. The following is a simple sample Java application that demonstrates how to use thejmapto generate a heap dump file.

Sample Java Application Code

public class JmapDemo {
    private static final int LIST_SIZE = 10000;

    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();

        // Fill the list to use a lot of memory
        for (int i = 0; i < LIST_SIZE; i++) {
            (new byte[1024]); // 1KB per element
        }

        // To keep the object active and prevent it from being reclaimed by the GC
        keepReference(list);
    }

    private static void keepReference(List<Object> list) {
        // This method keeps a reference to the list, preventing it from being reclaimed.
        while (true) {
            try {
                // Let the thread sleep, simulating a long-running service.
                (5000); }
            } catch (InterruptedException e) {
                ().interrupt(); } catch (InterruptedException e) {
            }
        }
    }
}

utilizationjmapGenerate heap dump file

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . JmapDemoRun the application.
  2. Get Java Process ID

    • On the command line, use thejpscommand to view all Java processes and their PIDs.
  3. utilizationjmapGenerating Heap Dumps

    • Assuming that the PID of your Java application is 1234, use the following command to generate a heap dump file:
      jmap -dump:format=b,file= 1234
      
    • This command generates a file namedof the heap dump file.
  4. Analyzing Heap Dump Files

    • Use MAT (Memory Analyzer Tool) or other heap analysis tools to open thefile to analyze memory usage and potential memory leaks.
  5. utilizationjmapPrinting Heap Information

    • If you only need to see overview information about the heap, you can use:
      jmap -heap 1234
      
    • This prints out detailed information about the heap, including memory used, maximum memory, GC policy, and so on.
  6. utilizationjmapPrinting class loading information

    • To view class loader statistics, you can use:
      jmap -clstats 1234
      
    • This will print out the number of loaded classes and related information.
  7. utilizationjmapPrint finalizer queue

    • If you suspect that there is an object because of waitingfinalize()method while being held in memory and available for use:
      jmap -finalizerinfo 1234
      
    • This will print out the waitfinalize()information about the object of the method.

With this example, you can see thatjmapis a useful tool that can help you diagnose memory related problems such as memory leaks and high memory usage. The generated heap dump file can be further analyzed in depth using other analysis tools.

5. Use of jstat

jstatis a command line tool provided by the JDK for real-time monitoring of JVM performance metrics such as class loading, memory, garbage collection, and so on. The following is a simple sample Java application that demonstrates how to use thejstatto monitor the operation of the JVM.

Sample Java Application Code

public class JstatDemo {
    private static final int ARRAY_SIZE = 1000000;
    private static final byte[] data = new byte[1024 * 1024]; // 1MBarrays

    public static void main(String[] args) {
        // Simulating Memory Allocation
        for (int i = 0; i < ARRAY_SIZE; i++) {
            if (i % 100000 == 0) {
                // Simulating intermittent memory allocation
                data = new byte[1024 * 1024];
            }
        }

        // Simulation of long-running services
        while (true) {
            try {
                (1000); // hibernation1unit of angle or arc equivalent one sixtieth of a degree
            } catch (InterruptedException e) {
                ().interrupt();
            }
        }
    }
}

utilizationjstatMonitoring JVM performance metrics

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . JstatDemoRun the application.
  2. Get Java Process ID

    • On the command line, use thejpscommand to view all Java processes and their PIDs.
  3. utilizationjstatMonitoring GC Activity

    • Assuming your Java application's PID is 1234, use the following command to monitor GC activity:
      jstat -gc 1234
      
    • This will display GC related statistics such as S0C, S1C, S0U, S1U (young generation size and usage), EC, EU, OC, OU, MC, MU, etc.
  4. Monitoring class loading information

    • Use the following command to monitor class loader statistics:
      jstat -class 1234
      
    • This will display information such as the number of classes loaded, the number of classes unloaded, etc.
  5. Monitor compiled method information

    • Use the following command to monitor JIT compiler statistics:
      jstat -compiler 1234
      
    • This will display information such as the number of compilation tasks, compilation time, etc.
  6. Monitoring Memory Usage

    • Use the following command to monitor memory usage:
      jstat -gcutil 1234
      
    • This will show the utilization of heap memory, both young and old generations.
  7. Monitor thread activity

    • Use the following command to monitor thread statistics:
      jstat -thread 1234
      
    • This will display information such as the total number of threads, the number of live threads, and the number of peak threads.
  8. Monitor synchronization blocking information

    • Use the following command to monitor synchronization blocking information:
      jstat -sync 1234
      
    • This displays statistics on synchronization operations, such as monitor lock contention.

With this example, you can see thatjstatis a real-time monitoring tool that can help you understand the operation of the JVM , especially useful in performance tuning and troubleshooting . By monitoring different performance metrics, you can quickly pinpoint problems and take appropriate action.

6. Using jcmd

jcmd is a versatile command line tool for executing administrative and diagnostic commands to obtain information about the Java Virtual Machine (JVM) and Java applications. The following is a simple example of a Java application that demonstrates how to use thejcmd to monitor and manage the operation of the JVM.

Sample Java Application Code

public class JcmdDemo {
    private static final int LIST_SIZE = 10000;

    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();

        // Filling the list to use a lot of memory
        for (int i = 0; i < LIST_SIZE; i++) {
            (new byte[1024]); // each element1KB
        }

        // Simulation of long-running services
        while (true) {
            try {
                (1000); // hibernation1unit of angle or arc equivalent one sixtieth of a degree
            } catch (InterruptedException e) {
                ().interrupt();
            }
        }
    }
}

utilizationjcmdMonitoring and managing the JVM

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • utilizationjava -classpath . JcmdDemoRun the application.
  2. Get Java Process ID

    • On the command line, use thejpscommand to view all Java processes and their PIDs.
  3. utilizationjcmdGetting JVM information

    • Assuming that the PID of your Java application is 1234, use the following command to get basic information about the JVM:
      jcmd 1234 Help
      
    • This will display all availablejcmdcommands and their descriptions.
  4. Getting the thread stack trace

    • Use the following command to get a stack trace of all threads:
      jcmd 1234 
      
    • This will output the call stack for each thread.
  5. Monitoring GC Activity

    • Use the following command to monitor GC activity:
      jcmd 1234 GC.class_histogram
      
    • This will display statistics for all loaded classes.
  6. Generate heap dump file

    • Use the following command to generate a heap dump file:
      jcmd 1234 GC.heap_dump /path/to/
      
    • This generates a file namedof heap dump files that you can analyze using MAT (Memory Analyzer Tool) or other heap analysis tools.
  7. Monitoring Memory Usage

    • Use the following command to monitor memory usage:
      jcmd 1234 GC.heap_info
      
    • This will display detailed information about the heap memory, including the size of the younger and older generations.
  8. Monitor thread status

    • Use the following command to monitor the thread status:
      jcmd 1234 
      
    • This will show the state and stack trace of all threads.
  9. Monitoring Compilation Tasks

    • Use the following command to monitor the compilation task:
      jcmd 1234 
      
    • This will display information about the code compiled by the JIT compiler.
  10. Monitoring class loading information

    • Use the following command to monitor class loading information:
      jcmd 1234 
      
    • This will display class loader statistics.

With this example, you can see thatjcmdis a powerful tool that can perform a variety of management and diagnostic commands. It not only helps you monitor the operation of the JVM , but also generates heap dump files for in-depth analysis .

7. Analyzing GC logs

Analyzing GC (garbage collection) logs is one of the most important tools for monitoring and optimizing the performance of Java applications.GC logs contain detailed information about when the JVM performs garbage collection, such as heap memory usage before and after the collection, the time taken for the collection, and so on. The following is a simple sample Java application that demonstrates how to generate GC logs and use an analysis tool to interpret these logs.

Sample Java Application Code

import ;
import ;

public class GcLogDemo {
    

    public static void main(String[] args) {
        List<Byte[]> list = new ArrayList<>();

        // JVM parameter settings to generate GC logs
        // -Xlog:gc*:file= Indicates that all GC-related logs should be logged to a file.
        // -Xms100m -Xmx100m sets the JVM's initial heap size and maximum heap size to 100MB.
        // JVM parameters should be placed in the java command, e.g.:
        // java -Xlog:gc*:file= -Xms100m -Xmx100m -classpath . GcLogDemo

        for (int i = 0; i < LIST_SIZE; i++) {
            // Allocate memory, trigger GC
            (new Byte[1024]); }
        }

        // Give the GC a chance to execute
        while (true) {
            try {
                (1000); } catch (InterruptedException e) {
            } catch (InterruptedException e) {
                ().interrupt();
            }
        }
    }
}

Interpreting GC Logs with Analytics Tools

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • When running the application, make sure that the JVM parameters for generating GC logs are included, as shown in the comment above.
  2. Generate GC logs

    • After running the application for a while, it will generate GC logs to a specified file (e.g.)。
  3. Using the GC Log Analysis Tool

    • A variety of tools can be used to analyze GC logs, such as GCViewer, GCEasy, jClarity, and others.
    • In the case of GCViewer, for example, you can drag and drop a GC log file into the GCViewer application, or use theFile -> Opento load the log file.
  4. Analyzing GC Log Contents

    • In the GCViewer, you can see an overview of GC, including the type of GC (Minor GC, Major GC, Full GC, etc.).
    • Observe the point in time when the GC occurs, and the time taken by each GC.
    • Analyze heap memory usage, including Eden areas, Survivor areas, old ages, and more.
  5. Identify performance bottlenecks

    • If you find that GCs are taking too long or occurring too often, this could be a sign of a performance bottleneck.
    • Analyzing the GC logs can help you determine if you need to adjust the JVM's memory settings or garbage collector strategy.
  6. Adjusting JVM Parameters

    • Depending on the results of the analysis of the GC logs, you may need to adjust parameters such as the heap size, the ratio of Eden and Survivor zones, the garbage collector type, and so on.
  7. Re-run and monitor

    • After adjusting the JVM parameters, re-run the application and monitor the GC logs to verify if performance has improved.

With this example, you can see how to monitor and optimize the garbage collection performance of your Java application by generating and analyzing GC logs. This is critical to ensure the stability and responsiveness of your application.

8. Use of MAT (Memory Analyzer Tool)

MAT (Memory Analyzer Tool) is an open source Java heap analyzer that can help us find memory leaks and optimize memory usage. The following is a simple example of a Java application that will generate a heap dump file, which we can then analyze using MAT.

Sample Java Application Code

import ;
import ;

public class MatDemo {
    private static List<Object> leakedObjects = new ArrayList<>();

    public static void main(String[] args) {
        // Simulate a memory leak: keep creating new objects and retaining references to them
        for (int i = 0; i < 10000; i++) {
            (new byte[1024]); // 1KB per element
        }

        // Trigger the heap dump, either automatically via the -XX:+HeapDumpOnOutOfMemoryError parameter
        // or by programmatically calling () to suggest that the JVM perform garbage collection
        // Then use the jmap tool to manually trigger a heap dump.
        try {
            ("Initiating heap dump - please wait...") ...") ;)
            // Assuming the jmap tool has already generated the heap dump file.
            // If it needs to be triggered programmatically, use ().gc(); // and then call (5000); // and then call (5000).
            // Then call (5000); to give the GC enough time to execute.
            // Then use jmap to generate a heap dump: jmap -dump:format=b,file= <pid>.
            (5000); }
        } catch (InterruptedException e) {
            ().interrupt(); }
        }

        // The program will keep running to wait for the MAT to be analyzed
        while (true) {
            try {
                (60000); // Sleep for 60 seconds
            } catch (InterruptedException e) {
                ().interrupt();
            }
        }
    }
}

Analyzing Heap Dump Files with MAT

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • To run the application, make sure to pass the JVM parameters or thejmapThe tool generates heap dump files, such as
  2. Launch MAT

    • Download and launch the MAT tool.
  3. Load Heap Dump File

    • In MAT, select "File" -> "Open Heap Dump", and then select the previously generatedDocumentation.
  4. Analyzing memory usage

    • MAT will analyze the heap dump file and present overview information, including memory usage overview, class instances, GC roots, and more.
  5. Finding Memory Leaks

    • Using MAT's "Analyzer" -> "Run" function, MAT will analyze possible memory leaks.
    • Check the "Leak Suspects Report", which will list possible memory leaks.
  6. Viewing references to objects

    • In the Dominator Tree view, you can see which objects are taking up the most memory.
    • In the Reference Chain view, you can see the path where the object is referenced.
  7. Analyzing specific objects

    • If you suspect an object has a memory leak, find the class in the Classes view and double-click on the instance to see the details.
  8. Using OQL Queries

    • MAT supports the Object Query Language (OQL), which you can use to query specific collections of objects or schemas.
  9. Export and save analysis results

    • You can export the analysis results as a report for further analysis or documentation.

With this example, you can see that MAT is a powerful tool that can help you analyze Java heap dump files, find memory leaks and optimize memory usage.MAT provides a wealth of views and queries that make the analysis process more efficient and in-depth.

9. Use of Profilers

Profilers are a class of tools for performance analysis that help developers identify performance bottlenecks in their applications. Below is a simple sample Java application that demonstrates how to use Profilers tools such as JProfiler or YourKit Java Profiler to monitor and analyze the performance of an application.

Sample Java Application Code

public class ProfilerDemo {
    private static final int NUM_ITERATIONS = 1000000;

    public static void main(String[] args) {
        // Perform some computationally intensive tasks
        long result = computeSum(0, NUM_ITERATIONS);

        // Simulation of long-running services
        while (true) {
            try {
                (1000); // hibernation1unit of angle or arc equivalent one sixtieth of a degree
            } catch (InterruptedException e) {
                ().interrupt();
            }
        }
    }

    private static long computeSum(long start, long end) {
        long sum = 0;
        for (long i = start; i < end; i++) {
            sum += i;
        }
        return sum;
    }
}

Monitoring and analyzing performance with Profilers tools

  1. Compile and run the sample application

    • utilizationjavac Compile Java code.
    • When running the application, make sure the Profilers tool is launched and the application is attached to Profilers.
  2. Attaching Profilers to Applications

    • Open a Profilers tool such as JProfiler or YourKit Java Profiler.
    • In Profilers, select "Attach to Application" and select the runningProfilerDemoProcess.
  3. Monitor CPU usage

    • Monitor the application's CPU usage in Profilers' CPU Profiling view.
    • Identify the method that takes up the most CPU time, which may be a performance bottleneck.
  4. Analyzing Memory Usage

    • Use the Memory Analysis feature to monitor your application's memory usage.
    • View memory allocations and identify memory leaks or highly memory-consuming classes.
  5. Recognizing thread activity and lock contention

    • Monitor thread activity to see the status of threads and lock usage.
    • Identify deadlocks or thread contention, which can affect the response time of an application.
  6. Perform sampling analysis

    • Use Profilers' Sample Analysis feature to collect call data over time.
    • Analyze the sampling results to identify hot methods and call paths.
  7. Using the Call Tree View

    • Check out the call tree view to understand the hierarchy and time consumption of method calls.
  8. Implementation of analytical methods

    • Identify the methods that take the longest to execute and see their callers and callees.
  9. Optimized code

    • Based on the results of the analysis, the code is optimized to improve performance, e.g. by reducing unnecessary calculations, improving data structures or algorithms.
  10. Reanalyze the optimized code

    • After optimizing the code, rerun the Profilers analysis to verify the performance improvements.

With this example, you can see how the Profilers tool helps developers monitor and analyze the performance of Java applications. By identifying performance bottlenecks and memory problems, developers can take appropriate optimization measures to improve application efficiency and responsiveness.

10. Finally

In practice, we also need to monitor system resources, such as monitoring the use of system resources such as CPU, memory, disk I/O and network to determine whether the problem is caused by system resource limitations. Usually you can also read and understand the JVM specification, V brother recommended a JAVA programmer manual book "JAVA Virtual Machine Specification", highly recommended to read it well oh. If the content of this article is helpful to you, the trouble is that a key to three companies to add attention to the programmer's road, we help each other forward.