Bytecode enhancement-based Java memory leak detection method and system
By employing bytecode-enhanced non-intrusive monitoring and weak reference technology, combined with multi-dimensional analysis, the accuracy and false positive rate issues of Java memory leak detection are resolved, achieving high-efficiency memory leak detection with low overhead.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-30
- Publication Date
- 2026-03-10
AI Technical Summary
Existing Java memory leak detection methods cannot achieve accurate and early automatic location of memory leak sources with low overhead and without affecting online services. They also have a high false alarm rate and cannot accurately locate the leaking object.
Object creation is monitored using a non-intrusive method based on bytecode enhancement. Weak reference technology is used to record lifecycle information, and multi-dimensional correlation analysis is performed in an independent analysis service. By combining weak references and reference queues, alarm information is generated to confirm memory leaks.
It achieves high-precision memory leak detection with low overhead, reduces false alarm rate, can accurately locate leaked classes and provide detailed object statistics, ensuring that the monitoring system does not affect business performance.
Smart Images

Figure CN121636285A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of memory leak detection technology, and in particular to a Java memory leak detection method and system based on bytecode enhancement. Background Technology
[0002] In the field of Java application performance monitoring, online detection methods for memory leaks face significant challenges. Traditional detection methods mainly fall into two categories: One type is deep analysis methods, such as heap dump analysis. This method obtains a complete snapshot of the application's memory at a specific moment and then performs offline analysis to accurately locate the leaking object. However, performing a heap dump causes the application to pause for a long time, making it unsuitable for routine use in online production environments, and it is a post-event analysis that cannot provide early warnings.
[0003] Another type is macro-level monitoring methods, such as monitoring JVM heap memory usage using APM tools. This method has low overhead and can run for a long time, but its monitoring granularity is too coarse. When a continuous increase in memory usage is detected, this method can only indicate that "a memory leak has occurred," but cannot accurately pinpoint which (or which) specific class of objects is causing the abnormal increase. Subsequent investigation still requires complex deep analysis methods for manual investigation, which is inefficient and has a high false alarm rate.
[0004] In summary, existing memory leak detection methods cannot achieve accurate, early, and automatic location of the source of memory leaks with low overhead and without affecting online services, and therefore need to be improved. Summary of the Invention
[0005] To address the technical problem that existing memory leak detection methods cannot achieve accurate and early automatic location of memory leak sources with low overhead and without affecting online services, this application provides a Java memory leak detection method and system based on bytecode enhancement.
[0006] Firstly, this application provides a Java memory leak detection method based on bytecode enhancement, employing the following technical solution: Within a Java application, the creation of objects of a specified class is monitored in a non-intrusive manner. Based on weak reference technology, the lifecycle information of the monitored objects is recorded, and raw statistical data is generated. Here, the monitored objects refer to objects of the specified class being monitored. In an analytics service independent of the Java application, the raw statistical data is periodically acquired, and multi-dimensional correlation analysis is performed on the raw statistical data; wherein, the multi-dimensional analysis includes at least a quantitative dimension analysis of the growth rate of the number of monitored objects and a time dimension analysis based on the survival time of the monitored objects; The system integrates the results of multi-dimensional correlation analysis to determine whether a memory leak has occurred. Based on different preset risk conditions, it triggers and outputs corresponding alarm information when any risk condition is met, so that the administrator can be informed.
[0007] By adopting the above technical solution, the lifecycle information of objects of a specified class (i.e., the monitored object) is monitored in a non-intrusive manner and using weak reference technology. Then, in an analysis service independent of Java applications, the analysis determines whether memory leaks have occurred. This decouples high-performance data collection (within the business JVM) from computationally complex intelligent analysis (in an independent service), ensuring that the complex analysis process no longer affects the performance of business applications. In addition, multi-dimensional correlation analysis refines the granularity of the monitored object analysis from the macroscopic JVM memory usage rate to the microscopic behavior of specific class objects in terms of quantity and time. It can directly locate the suspected class causing memory growth (such as UserSession), answering the key question of "what object is leaking", rather than just "whether memory is leaking". Furthermore, the results of multi-dimensional correlation analysis are fused and judged. This method achieves cross-validation of abnormal signals from multiple dimensions, which can effectively distinguish between normal enterprise business peaks (which may only trigger anomalies in the quantity dimension) and true memory leaks (which usually trigger anomalies in both the quantity and time dimensions). This reduces the false alarm rate from the excessively high level of traditional APM tools to below 5%, making alerts more actionable.
[0008] Optionally, the lifecycle information includes the timestamp of the monitored object's creation. The method of recording the lifecycle information of the monitored object based on weak reference technology includes: When a monitored object is detected to be created, a weak reference is created to reference the monitored object, and the currently created weak reference is associated with a reference queue managed by the reclaimer; at the same time, a tracking information metadata containing the creation timestamp of the monitored object is created, and the weak reference is associated with the tracking information metadata and stored. The reference queue is continuously monitored. When a weak reference created before the current time is captured in the reference queue, it is considered that the monitored object corresponding to the captured weak reference has been reclaimed by the reclaimer. At this time, the association between the captured weak reference and the corresponding tracking information metadata is released, and the original statistics are updated. The monitored objects that have not been reclaimed by the reclaimer are considered to be in a live state. The original statistics include: the number of live monitored objects in each specified class, and the set of creation timestamps of the live monitored objects.
[0009] By adopting the above technical solution, a weak reference is a reference type that does not prevent the referenced object from being garbage collected. The monitoring system "observes" objects through weak references but never holds "strong references" to the objects. When the garbage collector determines the liveness of an object, it completely ignores the existence of weak references. Therefore, even if the monitoring system is running, a business object that should be garbage collected will be collected normally. This fundamentally eliminates any new memory leaks that may be caused by introducing monitoring, which is the primary prerequisite for this solution to be applied in a production environment. In addition, by creating a weak reference and recording metadata only once when the object is created, and by monitoring and cleaning the reference queue through an asynchronous thread, the main business thread is not blocked, ensuring that the overhead of the entire tracing process is extremely low, which can meet the requirements of long-term operation in a production environment. Furthermore, by combining "creation timestamps" with "reference queue reclamation events," precise lifecycle information is established for each monitored object. In summary, this solution's combination of weak references, reference queues, and timestamp metadata, under the constraints of absolute safety and extremely low overhead, successfully captures the transient object creation and destruction events that originally occurred in the JVM black box, transforming them into precise, time-series data streams usable by subsequent intelligent analysis systems. Optionally, the multi-dimensional correlation analysis also includes memory dimension analysis based on JVM heap memory usage trends; The process involves fusing the results of multi-dimensional correlation analysis to determine whether a memory leak has occurred, and triggering corresponding alarm information when any of the preset risk conditions are met, including: When the quantitative dimension analysis of the growth rate of the number of monitored objects indicates that the growth rate of the monitored objects of the target class exceeds a preset first threshold, an abnormal growth rate alarm is triggered; and the alarm information is output; wherein, the target class refers to any specified class. When the time dimension analysis based on the survival time of the monitored object indicates that the number of monitored objects with excessively long survival time exceeds a preset second threshold, an abnormal alarm for excessively long survival time is triggered, and an abnormal alarm for excessively long survival time is output. When the memory dimension analysis based on JVM heap memory usage trends indicates that JVM heap memory is showing a continuous upward trend, a memory trend anomaly alarm is triggered, and memory trend anomaly alarm information is output. When multiple alarms are triggered simultaneously for the same target class, including abnormal growth rate alarm, abnormal long survival time alarm, and abnormal memory trend alarm, it is determined that the target class has a memory leak, and a memory leak alarm message is triggered and output.
[0010] By adopting the above technical solution, the effect of "multi-dimensional and fine-grained monitoring" is achieved, which makes early detection possible. In addition, a memory leak is only determined when all trigger alarms are met at the same time. This operation significantly reduces the false alarm rate and achieves the effect of intelligent confirmation.
[0011] Optionally, the "ultra-long survival" refers to the duration of being in a survival state exceeding a preset third threshold. The step of fusing and determining whether a memory leak has occurred based on multi-dimensional correlation analysis results, and triggering the output of corresponding alarm information when any risk condition is met according to preset different risk conditions, also includes: A monitoring object survival time model based on historical data is established for each specified class based on a preset model. Using the lifespan model of the monitoring objects corresponding to the target class, predict the expected recycling time limit of the monitoring objects of the target class; The preset recycling time limit is used as the third threshold for determining whether the monitored object of the target class has survived for an excessively long period of time.
[0012] By adopting the above technical solution, customized memory leak detection for specified classes with different business characteristics is achieved, making the monitoring strategy more targeted. Through prediction based on historical behavior, it is possible to more accurately identify truly "abnormal" live objects, thereby significantly reducing the false alarm rate of time-dimensional analysis. Operation and maintenance personnel no longer need to manually study and set static timeout thresholds for thousands of different classes, greatly simplifying the operation and maintenance configuration work.
[0013] Optionally, the method further includes: Initialize and maintain a global weak reference object pool to store reusable weak reference instances, while continuously monitoring and counting the creation frequency of objects of different specified classes; Based on the creation frequency of each specified class of objects, a prediction engine is established for each specified class, and the prediction engine is used to predict the expected number of objects created for the corresponding specified class in the future time window. Based on the expected number of objects created for each specified class and the corresponding preset monitoring priority, the weak reference resource quota for each specified class is dynamically calculated; where, the higher the monitoring priority, the larger the corresponding weak reference resource quota, that is, the larger the number of weak reference instances that can be allocated. Creating a weak reference to refer to the monitored object includes: If and only if the current weak reference resource quota of the specified class to which the currently created monitoring object belongs is less than the corresponding weak reference resource quota, then a weak reference instance is allocated from the weak reference object pool to reference the currently created monitoring object, and the current weak reference resource quota of the specified class to which the currently created monitoring object belongs is updated. The method further includes: When global resource shortage is detected in the weak reference object pool, a sampling monitoring strategy is implemented for the low-priority specified classes according to the monitoring priority of each specified class. The sampling monitoring strategy is used to reduce the number of weak reference instances allocated from the weak reference object pool to the low-priority specified class objects.
[0014] By adopting the above technical solution, and by establishing a weak reference object pool and realizing instance reuse, this invention fundamentally avoids the memory allocation and garbage collection (GC) pressure caused by creating a new weak reference instance for each monitored object. This keeps the monitoring system's memory footprint stable and low, achieving lightweight and efficient monitoring. Through a predictive quota mechanism, the system no longer blindly and equally allocates resources. Instead, it precisely allocates resources based on the actual activity (object creation frequency) and importance (priority) of each class. This maximizes global resource utilization, avoiding resource waste on high-frequency but non-critical specified classes, or resource shortages on low-frequency but critical specified classes. Traditional resource allocation is static or reactive. This invention, through a predictive engine, can proactively predict future resource needs based on historical data. This allows the system to prepare in advance (pre-allocate quotas) before peak resource demand arrives, achieving a leap from "passive response" to "proactive planning," greatly improving the system's smoothness and stability. The sampling monitoring strategy is key to the system's robustness. When global resources are strained, the system does not simply deny service or crash, but proactively releases resources by reducing the monitoring granularity (sampling) of low-priority classes. This is an intelligent and strategic degradation that sacrifices the accuracy of some non-core functions in exchange for the continued operation of the core functions of the entire monitoring system.
[0015] Optionally, the sampling monitoring strategy for low-priority specified classes includes: Set the low-priority designated class of the real-time sampling monitoring strategy as the degradation class, and set the sampling rate for each degradation class; According to the sampling rate, by random sampling, some newly created objects in the downgraded class are used as monitoring objects, weak reference instances are allocated and tracking information metadata is created; Based on the tracking metadata corresponding to the monitored objects of the downgraded class and the lifecycle state of the allocated weak reference instances, a multi-dimensional correlation analysis is performed on the monitored objects of the downgraded class.
[0016] By adopting the above technical solution, and by setting low-priority classes as "degraded classes" and implementing sampling, the system systematically and controllably reduces the consumption of weakly referenced instances by these classes. The valuable resources forcibly released are immediately reallocated by the system to absolutely ensure uninterrupted full monitoring of high-priority classes. This prevents the system from completely crashing when overall resources are strained; instead, it sacrifices the accuracy of secondary functions to maintain the operation of core functions. Sampling does not completely abandon monitoring but rather transforms from a "full survey" to a "sampling survey." Through random sampling and statistical analysis, the system can still estimate overall abnormal trends (such as whether the number is abnormally increasing or whether objects are generally surviving for excessively long periods) based on small sample data.
[0017] Optionally, the method further includes: Whenever the current weak reference resource quota used by the specified class to which the currently created monitoring object belongs is greater than or equal to the corresponding weak reference resource quota, an insufficient quota event is generated and recorded. Regularly monitor and statistically analyze quota shortage events corresponding to different specified categories, and calibrate and optimize the prediction engine based on the analysis of the quota shortage events.
[0018] By adopting the above technical solution, the "quota shortage event" is a clear negative feedback signal, directly indicating that the prediction engine has underestimated the actual creation frequency of objects of that type. The system periodically collects and analyzes these signals, using them as a direct basis for correcting the prediction model (such as adjusting the parameters or weights of the time-series prediction algorithm). This operation ensures that the prediction engine is no longer static; it adaptively adjusts with changes in business models (such as changes in user activity time or a surge in certain types of objects due to the launch of new features). This makes the system's resource quota allocation increasingly accurate, reducing the occurrence of future quota shortage events from the source.
[0019] Secondly, this application provides a Java memory leak detection system based on bytecode enhancement, employing the following technical solution: The non-intrusive probe module is used to monitor the creation of objects of a specified class in a non-intrusive manner within a Java application. It records the lifecycle information of the monitored objects based on weak reference technology and generates raw statistical data. The monitored objects refer to objects of the specified class being monitored. The intelligent analysis engine module is used to periodically acquire the raw statistical data in an analysis service independent of the Java application, and perform multi-dimensional correlation analysis on the raw statistical data; wherein, the multi-dimensional analysis includes at least a quantitative dimension analysis of the growth rate of the number of monitored objects and a time dimension analysis based on the survival time of the monitored objects; The fusion decision and alarm module is used to determine whether a memory leak has occurred based on the results of multi-dimensional correlation analysis, and to trigger the corresponding alarm information when any risk condition is met, so that the administrator can be informed.
[0020] Thirdly, this application provides a Java memory leak detection device based on bytecode enhancement, including a memory and a processor, wherein the memory stores a computer program that can be loaded by the processor and executed as described in any of the first aspects.
[0021] Fourthly, this application provides a computer-readable storage medium storing a computer program that can be loaded by a processor and execute the method described in any of the first aspects.
[0022] In summary, this application includes at least one of the following beneficial technical effects: 1. This application achieves the capability of high-precision memory leak detection in a production environment. The CPU overhead of the agent probe is controlled within 1%, and the memory usage does not exceed 3% of the total application memory. At the same time, it can accurately locate the specific leak class name and provide detailed object statistics information; 2. Furthermore, through the innovative combination of weak references and reference queues, the monitoring system itself is guaranteed to never hold any strong references to the monitored objects; even after long-term operation, the memory usage of the monitoring tool remains stable and will not interfere with the application's garbage collection. 3. Furthermore, this application transforms the complex analysis work that originally required professional JVM knowledge into a standardized automatic monitoring service; the system can automatically identify abnormal patterns, generate alarms, directly output key information such as leaked class names, number of objects, and lifespan, and provide relevant troubleshooting suggestions; 4. Furthermore, through the probe-analyzer separation architecture, this application achieves complete decoupling of data acquisition and analysis processing; the Agent probe and monitoring service can be deployed and upgraded independently, the analysis service supports horizontal scaling to monitor multiple application instances, and the failure of the monitoring service will not affect the normal operation of business applications. Attached Figure Description
[0023] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0024] Figure 1 This is a flowchart illustrating the Java memory leak detection method based on bytecode enhancement disclosed in an embodiment of this application.
[0025] Figure 2 This is a structural block diagram of the Java memory leak detection system based on bytecode enhancement disclosed in the embodiments of this application.
[0026] Figure labeling: 201, Non-invasive probe module; 202, Intelligent analysis engine module; 203, Fusion decision and alarm module. Detailed Implementation
[0027] The following is in conjunction with the appendix Figure 1-2 This application will be described in further detail.
[0028] This application discloses a Java memory leak detection method based on bytecode enhancement (hereinafter referred to as the memory leak method), the execution body of which is a Java memory leak detection system based on bytecode enhancement (hereinafter referred to as the memory leak system). The following will combine... Figure 1 This section details the specific steps involved in executing memory leak methods in a memory leak system.
[0029] S101 monitors the creation of objects of a specified class in a non-intrusive manner within a Java application. It records the lifecycle information of the monitored objects based on weak reference technology and generates raw statistical data. The monitored object refers to an object of the specified class being monitored. S102, in the analysis service independent of Java applications, periodically acquires raw statistical data and performs multi-dimensional correlation analysis on the raw statistical data; among which, the multi-dimensional analysis includes at least the quantitative dimension analysis of the growth rate of the number of monitored objects and the time dimension analysis based on the survival time of monitored objects; S103 performs a fusion analysis based on the results of multi-dimensional correlation analysis to determine whether a memory leak has occurred. Based on different preset risk conditions, it triggers the output of corresponding alarm information when any risk condition is met, so that the administrator can be informed.
[0030] S101, "Monitoring the creation of objects of a specified class in a non-intrusive manner within a Java application," includes: By using Java Agent technology, monitoring code can be non-intrusively injected into the constructor of a specified class to trigger tracing logic when the monitored object is created; In S102, the periodic acquisition of raw statistical data is accomplished through a standard JMX interface; The lifecycle information includes the timestamp of the monitored object's creation. The "recording of the lifecycle information of the monitored object based on weak reference technology" in S101 includes: S1011, When the monitoring object is detected to be created, a weak reference is created to reference the monitoring object, and the currently created weak reference is associated with a reference queue managed by the garbage collector; at the same time, a tracking information metadata containing the creation timestamp of the monitoring object is created, and the weak reference is associated with the tracking information metadata and stored. S1012, continuously monitor the reference queue. When a weak reference created before the current time is captured in the reference queue, it is considered that the monitored object corresponding to the captured weak reference has been reclaimed by the garbage collector. At this time, the association between the captured weak reference and the corresponding tracking information metadata is released, and the original statistics are updated. Among them, the monitored objects that have not been reclaimed by the garbage collector are considered to be in a live state. The original statistics include: the number of live monitored objects in each specified class, and the set of creation timestamps of the live monitored objects.
[0031] Furthermore, the multi-dimensional correlation analysis also includes memory dimension analysis based on JVM heap memory usage trends; S103 specifically includes the following steps: When the quantitative analysis of the growth rate of the number of monitored objects indicates that the growth rate of the monitored objects of the target class exceeds a preset first threshold, an abnormal growth rate alarm is triggered; the alarm information is output; where the target class refers to any specified class. When the time dimension analysis based on the survival time of the monitored objects indicates that the number of monitored objects with excessively long survival time exceeds the preset second threshold, an abnormal alarm for excessively long survival time is triggered, and an abnormal alarm for excessively long survival time is output. When memory dimension analysis based on JVM heap memory usage trends indicates that JVM heap memory is showing a continuous upward trend, a memory trend anomaly alarm is triggered, and memory trend anomaly alarm information is output. When multiple alarms are triggered simultaneously for the same target class, including abnormal growth rate alarm, abnormal long survival time alarm, and abnormal memory trend alarm, it is determined that a memory leak has occurred in the target class, and a memory leak alarm message is triggered and output.
[0032] After generating an alert, it also provides code investigation suggestions for suspected leaks, including checking static collections, event listeners, or cached references.
[0033] In implementation, operations personnel deploy a Java Agent probe by adding the command `-javaagent: / path / to / memory_leak_detector_agent.jar` to the startup parameters of the monitored Java reference (such as an e-commerce website server). The Agent's configuration file specifies the classes to be monitored (i.e., the specified classes mentioned earlier), such as `com.example.UserSession`. Multiple classes can be specified, and the monitored object is the object corresponding to any of these specified classes. When the JVM starts and loads these specified classes, the Java Agent automatically inserts a line of code `ObjectTracker.track(this);` at the end of the constructor bytecode of the target class (such as `UserSession`) using the `ClassFileTransformer` component. This process is completely transparent to the business code, achieving zero intrusion.
[0034] When a user logs into a business system (such as an e-commerce website), and the business code executes `new UserSession()`, the `ObjectTracker.track(this)` method, which is embedded in the probe of the memory leak detection system, is called. This method internally performs the following core operations: 1. Create weak references and tracking metadata: Create a java.lang.ref.WeakReference instance for the newly created UserSession object (hereinafter referred to as the monitoring object). At the same time, create a TrackInfo object (tracking metadata), whose core field is createTimestamp (the timestamp of creation), and its value is System.currentTimeMillis().
[0035] 2. Associating with a Reference Queue: When creating the weak reference mentioned above, a global `java.lang.ref.ReferenceQueue` (reference queue) is passed as a parameter. This operation associates the weak reference with the reference queue, which is equivalent to registering a listener with the garbage collector (GC) (i.e., associating the weak reference with the reference queue): when this `UserSession` object is garbage collected, please put its corresponding weak reference into this reference queue.
[0036] 3. Association Storage: A key-value pair (e.g., (WeakReference, TrackInfo)) describing the association between weak references and tracking information metadata is stored in a global, line-safe ConcurrentHashMap. This Map constitutes a list of all monitored, live monitoring objects.
[0037] After completing the above operations, a low-priority background daemon thread started by the probe is used to continuously monitor the reference queue, and the following operations are performed during the monitoring process: 1. Capture and Reclaim Time: When a user logs out or the session times out, the UserSession object should be reclaimed. If it is not reclaimed due to a code defect, this step will not be triggered. If it is reclaimed normally, the GC will put its corresponding weak reference object into the reference queue. The daemon thread captures this weak reference using the referenceQueue.poll() method.
[0038] 2. Cleanup and Update: Based on the captured weak references, remove the corresponding key-value pairs from the ConcurrentHashMap and update the internal mechanism (such as adding "total number of reclaimed items").
[0039] 3. Generate raw statistics: The probe exposes raw statistics through JMX MBeans. These statistics are calculated in real time by the aforementioned Map and mainly include: liveCount: The number of monitored objects in a live state (i.e., existing in the Map) in each specified class (e.g., UserSession). creationTimestamps: The collection of creation timestamps for all currently live monitored objects.
[0040] In summary, after completing all the steps described in S101, the memory leak detection system then executes S102, with the specific execution steps as follows: First, data is retrieved periodically: An analysis service is deployed independently in advance. The analysis service is independent of the Java application. Through the standard JMX interface, it connects to the JMX port referenced by the business every specified interval (such as 20 seconds) to read raw statistical data such as liveCount and creationTimestamps exposed by the probe.
[0041] Then, the memory leak detection system is used to perform multi-dimensional correlation analysis on the periodically retrieved data: Quantitative Dimension Analysis: Calculates the growth rate of monitored objects for each specified class (e.g., UserSession) within the most recent time window (e.g., 1 hour). For example, (current liveCount - liveCount one hour ago) / liveCount one hour ago. Compare this growth rate with a preset first threshold (e.g., 50%).
[0042] Time-based analysis: Iterate through the creationTimestamps collection of each specified class (e.g., UserSession class) and calculate the current survival time (i.e., current time - creation timestamp) of each monitored object. Count the number of objects whose survival time exceeds a reasonable business threshold (e.g., 30 minutes, i.e., excessively long survival). Compare this number with a preset second threshold (e.g., 100).
[0043] Memory dimension analysis: The analysis service also obtains historical data points of JVM old generation (Old / Tenured Generation) memory usage through JMX, and uses trend analysis algorithms (such as linear regression) to determine whether it shows a continuous upward trend.
[0044] Then, the memory leak detection system further executes S103, and the specific execution process is as follows: Based on the analysis results from S102, the analysis service triggers alarms of different levels in parallel: Growth Rate Anomaly Alarm: When the growth rate of any monitored object of a specified class (i.e., the target class, such as the UserSession class) exceeds the first threshold, an abnormal growth rate alarm is triggered and output. This alarm is used to indicate that an anomaly may exist.
[0045] Excessive Long Liveness Anomaly Alarm: When the number of monitored objects of any specified class (i.e., the target class, such as the UserSession class) whose liveness duration exceeds the preset third threshold exceeds the preset second threshold, an excessive long liveness anomaly alarm message is triggered and output. This alarm is a strong risk signal of memory leak.
[0046] Memory Trend Anomaly Alert: When the JVM heap memory is confirmed to be showing a continuous upward trend (e.g., the increase duration exceeds a preset duration), a memory trend anomaly alert is triggered and output. It should be noted that the specific content of the growth rate anomaly alert, the excessively long survival anomaly alert, and the memory trend anomaly alert should at least include the class name of the target class where the anomaly occurred, and the corresponding tag content for each alert (e.g., "growth rate anomaly," "excessively long survival anomaly," "memory trend anomaly").
[0047] Furthermore, the memory leak detection system integrates multi-dimensional analysis results for judgment: when multiple alarms are triggered simultaneously for the same target class (such as the UserSession class in this example), including abnormal growth rate alarms, abnormal long survival alarms, and abnormal memory trend alarms, it is determined that the target class has a memory leak, and the target class can be identified as the leaking class. At this time, the memory leak detection system triggers and outputs memory leak alarm information. The alarm information clearly indicates that the class name of the leaking class is com.example.UserSession, and includes key data evidence, which may include: the leaking class name: such as c `om.example.UserSession`; the number of monitored objects currently alive among all monitored objects corresponding to the leaked class; the abnormal growth rate of the leaked class; the number of monitored objects with extremely long survival times; JVM old generation memory usage (e.g., increasing from 45% two hours ago to 85%); the time point when the exception was first triggered (used to help trace code releases or configuration changes that may have caused the problem); and call stack sampling of high-frequency creation points (analyzing the most frequent code call paths that created these leaked objects from the creation timestamps and call stack information collected by the probe, providing developers with the most direct code investigation entry point). This key data evidence closely links the micro-level object behavior (the number of monitored objects for the leaked class only increases) with the macro-level system indicators (memory usage continues to rise), forming an irrefutable diagnostic report that greatly improves the credibility and operability of alerts.
[0048] Finally, when generating memory leak alerts, the memory leak detection system automatically matches and provides code investigation suggestions in a preset knowledge base based on the characteristics of the leaking class (such as the class name containing "Session"). For example, it suggests checking the reference configuration of global static Maps, event listeners, or caching frameworks (such as Ehcache, Guava Cache) to confirm that they do not hold strong references to UserSession objects.
[0049] Optionally, "extremely long survival" refers to the duration of survival exceeding a preset third threshold. S103 also includes the following steps: A monitoring object survival time model based on historical data is established for each specified class based on a preset model. By using the lifespan model of the monitoring objects corresponding to the target class, the expected recycling time limit of the monitoring objects of the target class is predicted; The preset recycling time limit is used as the third threshold to determine whether the monitored objects of the target class have survived for an excessively long period of time.
[0050] In implementation, this application further maintains an independent monitoring object survival time model for each monitored specified class (such as UserSession, ProductCache, etc.) within the analysis service. Specifically, whenever a monitored object is recycled, the probe, in addition to cleaning up the corresponding data, records the complete survival time of the recycled monitored object (complete survival time = recycling timestamp - creation timestamp) and reports this complete survival time as a survival time sample to the analysis service, using this survival market sample as the data source for the monitoring object survival time model. The analysis service then continuously collects these survival time samples for each monitored specified class. Initially, a simple sliding time window model can be used as the monitoring object survival time model (e.g., collecting survival time samples from the past 24 hours). As the number of samples accumulates, a more accurate historical distribution histogram can be constructed as the monitoring object survival time model. For example, statistics show that in the past 24 hours, 50% of UserSession objects were recycled within 5 minutes, 90% within 30 minutes, and 99.5% within 2 hours.
[0051] Next, the memory leak detection system uses the aforementioned monitoring object lifespan model to predict the expected recycling timeout for each monitored specified class, and uses this expected recycling timeout as the specific value of the third threshold for the corresponding specified class. Specifically, the expected recycling timeout for the monitored object of the target class can be calculated using high quantiles. For example, the specific implementation scheme when the target class is the UserSession class is as follows: For the UserSession class, the memory leak detection system calculates the 95th percentile of its historical lifespan (i.e., 95% of historical objects were garbage collected before this point in time). Let's assume the calculated value is T95 = 35 minutes. This means that, based on historical patterns, a UserSession class monitoring object surviving for more than 35 minutes is a very rare "outlier." Therefore, this 35 minutes can be used as a dynamic threshold (i.e., the third threshold) for determining whether a UserSession class monitoring object has an excessively long lifespan; this dynamic threshold replaces the initially manually set, fixed third threshold.
[0052] Next, during the time-dimensional analysis, the memory leak detection system will determine whether the monitored objects of the target class have exceeded their lifespan based on the third threshold corresponding to the target class. For example, the memory leak detection system obtains the creation timestamps of all currently surviving UserSession class monitored objects, calculates the current lifespan of each monitored object, compares the current lifespan of each monitored object with the corresponding latest updated dynamic threshold (e.g., 35 minutes), and counts the number of objects whose lifespan exceeds the dynamic threshold. If this number exceeds a preset threshold (i.e., the second threshold, e.g., 100), an excessively long lifespan anomaly alarm is triggered.
[0053] Furthermore, it should be noted that the aforementioned monitoring object survival time model and the dynamic threshold (i.e., the third threshold) corresponding to each specified class are not static. The analytics service periodically (e.g., hourly) recalculates the survival time distribution for the most recent time window (e.g., the past 24 hours) and updates the 95th percentile value. In this way, if the business model changes (for example, the company introduces a long session feature, and the average user login time increases), the dynamic threshold will automatically adapt.
[0054] Optionally, the memory leak detection method may also include the following steps: Initialize and maintain a global weak reference object pool to store reusable weak reference instances, while continuously monitoring and counting the creation frequency of objects of different specified classes; Based on the creation frequency of each specified class of objects, a prediction engine is built for each specified class, and the prediction engine is used to predict the expected number of objects of the corresponding specified class to be created in the future time window. Based on the expected number of objects created for each specified class and the corresponding preset monitoring priority, the weak reference resource quota for each specified class is dynamically calculated; where, the higher the monitoring priority, the larger the corresponding weak reference resource quota, that is, the larger the number of weak reference instances that can be allocated. The "Creating a weak reference to reference the monitored object" in S1011 also includes the following steps: If and only if the current weak reference resource quota of the specified class to which the currently created monitoring object belongs is less than the corresponding weak reference resource quota, then allocate a weak reference instance from the weak reference object pool to reference the currently created monitoring object, and update the current weak reference resource quota of the specified class to which the currently created monitoring object belongs. Whenever the current weak reference resource quota used by the specified class to which the currently created monitoring object belongs is greater than or equal to the corresponding weak reference resource quota, an insufficient quota event is generated and recorded. Memory leak detection methods also include: When global resource shortage is detected in the weak reference object pool, a sampling monitoring strategy is implemented for the low-priority specified classes according to the monitoring priority of each specified class. The sampling monitoring strategy is used to reduce the number of weak reference instances allocated from the weak reference object pool to low-priority specified class objects.
[0055] The sampling and monitoring strategy specifically includes the following steps: Set the low-priority designated class of the real-time sampling monitoring strategy as the degradation class, and set the sampling rate for each degradation class; Based on the sampling rate, by random sampling, some newly created objects in the downgraded class are used as monitoring objects, weak reference instances are allocated and tracking information metadata is created; Based on the tracking metadata corresponding to the monitored objects of the downgraded class, and the lifecycle state of the allocated weak reference instances, a multi-dimensional correlation analysis is performed on the monitored objects of the downgraded class.
[0056] In addition, the memory leak detection system is also used to periodically monitor and statistically analyze quota shortage events corresponding to different specified classes, and to calibrate and optimize the prediction engine based on the analysis of quota shortage events.
[0057] In implementation, this application constructs a memory leak monitoring resource management system capable of self-learning and self-optimization through five core components: building a resource pool, predictively allocating the number of weak reference instances for each specified class, implementing intelligent degradation for monitoring operations of each specified class, and adaptive feedback. Specifically, the memory leak detection system will perform the following steps: S1: Resource Pooling and Basic Monitoring When the probe of the memory leak detection system starts, a fixed-size WeakReferencePool is pre-initialized. This pool is implemented using a thread-safe queue (such as ConcurrentLinkedQueue) and is filled with a certain number (e.g., 10,000) of newly created empty WeakReference instances that are not associated with any objects. All WeakReference instances are associated with a unified ReferenceQueue at the time of creation.
[0058] When the probe intercepts the creation of a monitored object and executes the step of "recording the lifecycle information of the monitored object based on weak reference technology" as described in S101 above, it will synchronously update an internal statistics module. The internal statistics module maintains a frequency counter for each monitored specified class (such as UserSession), and counts the number of times each specified class object is created (creationsPerMinute) in a time sliding window (such as the past 1 minute).
[0059] S2: Predictive Quota Calculation The memory leak detection system runs a prediction engine that periodically pulls historical creationsPerMinute data for each specified class via JMX. For each specified class, the prediction engine uses a time-series prediction algorithm, such as Holt-Winters triple exponential smoothing, to capture the trend and seasonality of the historical creationsPerMinute data. The prediction engine is trained and periodically retrained using data from the past few hours. At the beginning of each quota calculation cycle (e.g., every 5 minutes), the prediction engine performs a prediction for each specified class, obtaining the expected number of object creations (N_forecast) for each specified class in the next quota calculation cycle.
[0060] Furthermore, the memory leak detection system configures a monitoring priority (e.g., "high priority," "low priority") for each specified class. The system uses a preset quota calculator to allocate resources to each specified class based on the predicted number of monitored objects created (N_forecast) and the monitoring priority. The calculation is: Quota = Base + (N_forecast * Priority_Weight). Here, Base is a preset basic quota guaranteed for each specified class, representing the minimum number of weak reference instances allocated to that class. This is a fixed preset value to prevent complete loss of monitoring for the specified class when the prediction is zero. Priority_Weight is a preset priority weight coefficient, with high-priority classes receiving the highest weight to ensure they receive sufficient resources. It should be noted that the total quota for all specified classes cannot exceed a certain percentage (e.g., 80%) of the total weak reference pool capacity, reserving a portion as a buffer.
[0061] S3: Intelligent Allocation, Degradation, and Sampling S31. Normal allocation process: When a specified class (using UserSession as an example below) object is created, the probe's ObjectTracker.track() is called. The default tracker checks the current used quota counter (UsedCount) of the UserSession class. If UsedCount < Quota_userSession (i.e., the resource quota Quota of the UserSession class), a weak reference instance is retrieved from the WeakReferencePool, reset, and points to the currently created UserSession object (i.e., "creating a weak reference to reference the currently created monitoring object" as described in S1011 above). Then, the UsedCount value of the UserSession class is incremented, updating the used quota counter value. If UsedCount ≥ Quota_userSession, this tracking is skipped (i.e., the newly created UserSession class object is ignored, and no weak reference instance is allocated to it), and an insufficient quota event is recorded. In other words, the lifecycle information of the newly created UserSession class object will only be recorded based on weak reference technology if and only if UsedCount < Quota_userSession.
[0062] Based on this allocation process, it can be seen that this application pre-creates several weak references and stores them as weak reference instances in a resource pool (WeakReferencePool). A maximum number of weak reference instances allocated from the resource pool (i.e., resource quota) is set for each specified class. When a specified class object is found to be created and the corresponding resource quota is not exceeded, a weak reference instance is allocated to the newly created specified class object, which implements the content of "creating a weak reference to reference the monitored object" in sub-step S101. At this point, the weak reference instance allocated to the resource pool is associated with the monitored object. When the background daemon thread captures the weak reference from the reference queue (indicating that the monitored object it points to has been garbage collected), in addition to cleaning up the corresponding TrackInfo metadata and removing the association with the monitored object, the memory leak detection system also cleans up and resets the weak reference instance, returning it to the global WeakReferencePool (weak reference object pool) for subsequent reuse. At the same time, the UsedCount count (used quota counter) of the specified class to which the monitored object originally associated with the weak reference instance belongs is decremented by one.
[0063] S32. Degradation and Sampling Process: The memory leak detection system also has a dedicated health monitoring thread that continuously checks the number of remaining instances in the WeakReferencePool. When the number of remaining instances falls below X% (e.g., 10%) of the total capacity, it is determined that global resources are strained, and a degradation mode is triggered.
[0064] Once in degrade mode, the memory leak detection system writes a "resource shortage" signal to a global status flag. All subsequent track() calls will check the priority of the specified class to which the corresponding monitored object belongs before allocating a weak reference instance.
[0065] For low-priority specified classes: immediately switch to sampling monitoring mode (i.e. become a degraded class), for example, only track 1% of creation events, or directly suspend the allocation of new resources.
[0066] For high-priority designated classes: their quotas and allocation processes remain completely unaffected, ensuring the integrity of core business monitoring. Simultaneously, the memory leak detection system will generate an "Monitoring system has been downgraded" operational alert to prompt administrators. When the remaining number of WeakReferencePool instances is ≥X% (e.g., 10%), the memory leak detection system automatically exits downgrade mode, and the monitoring policies for all designated classes revert to the normal allocation process described in S31.
[0067] For a specified class that is in sampling monitoring mode (i.e., becomes a degraded class), the memory leak detection system will perform the following operations on the degraded class: S321: Monitoring Degradation Classes Based on Sampling Rate When the system enables sampling monitoring for the downgraded class (taking LowPriorityClass as an example below) and sets the sampling rate to S (such as 1% or 0.01), the probe will generate a random number R (0 ≤ R < 1) whenever a newly created LowPriorityClass object is detected. Only when R < S will a weak reference be allocated to the monitored object and full-link tracing be performed (i.e., the steps corresponding to S101, S102, and S103); otherwise, it will be ignored.
[0068] S322: Multi-dimensional association analysis of degraded classes: For downgraded objects, the memory leak detection system will also perform multi-dimensional correlation analysis, specifically estimating the growth rate and long-term survival rate of downgraded objects.
[0069] Specifically, the memory leak detection system periodically defines the number of degraded class objects actually tracked (i.e., full-link tracing) according to the sampling rate (e.g., S) set in S31 as N_observed, and calculates the total number of degraded class objects estimated as N_estimated = N_observed / S. For example, if the sampling rate S = 1%, and 50 LowPriorityClass objects are actually observed to be alive, the memory leak detection system estimates the total number of alive objects to be approximately 50 / 0.01 = 5000.
[0070] The memory leak detection system then compares the currently calculated total quantity estimate N_estimated with the N_estimated calculated in the previous period, calculating the growth rate = (previous total quantity estimate N_estimated - previous period's N_estimated) / previous period's N_estimated. The growth rate is then compared with a preset first threshold. Following the logic for abnormal growth rate alerts described earlier, the system determines whether the growth rate of the degraded object is abnormal. If abnormal, an abnormal growth rate alert is triggered. This achieves quantitative dimension analysis of degraded objects.
[0071] Furthermore, the memory leak detection system periodically defines L_observed as the number of degraded objects with excessively long survival time (i.e., the duration of survival exceeds a preset third threshold) among the actual number of degraded objects tracked according to the sampling rate (e.g., S) set in S31. It then calculates the excessively long survival ratio among degraded objects, P_longLived = L_observed / N_observed; the total number of excessively long-surviving objects, L_estimated = the currently calculated total number estimate N_estimated * P_longLived. For example, if 10 out of 50 objects are observed to have excessively long survival time, the estimated excessively long survival ratio is 20%, and the estimated total number of excessively long-surviving objects is 10 / 0.01 = 1000. The memory leak detection system then compares the total number of excessively long-surviving objects, L_estimated, with the preset second threshold and, based on the excessively long survival anomaly alarm logic described above, determines whether an excessively long survival anomaly alarm has occurred for the degraded objects. If an anomaly is detected, an excessively long survival anomaly alarm is triggered, thus completing the time-dimensional analysis of the degraded objects.
[0072] Finally, for the downgraded class, the memory leak detection system uses the above-mentioned quantitative and temporal dimension analysis results, and then performs a multi-dimensional correlation analysis of the downgraded class monitoring objects according to the memory dimension analysis described above, and determines whether a memory leak has occurred.
[0073] S4: Adaptive Feedback Adjustment For the quota shortage events recorded earlier, the memory leak detection system periodically (e.g., every 5 minutes) pulls the count of quota shortage events from all probe nodes and aggregates them according to different specified categories to obtain the total number of quota shortage events (ShortageCount) occurring in the most recent window period (e.g., 5 minutes) for each specified category. Then, it calculates the quota shortage rate (ShortageRate) for each specified category: ShortageCount for the corresponding specified category / the total number of objects actually created in the most recent window period for the corresponding specified category. The prediction engine uses ShortageRate as an important correction signal. If ShortageRate is consistently (e.g., for N consecutive window periods, where N is a positive number greater than 0) higher than a preset threshold (e.g., 5%), it indicates that the current prediction engine systematically underestimates the object creation frequency of that category. At this time, the prediction engine will initiate a recalibration process: adjusting the model parameters (e.g., increasing the weight of the trend component in the Holt-Winters model to make it more sensitive to recent growth) to achieve correction. In the next quota calculation cycle, in addition to using the corrected prediction engine for prediction, a compensation factor, Compensation, will be introduced. The resource quota, Quota, will be corrected using Compensation, so that the final formula for calculating the resource quota is: Quota = Base + (N_forecast*Priority_Weight)+Compensation. Here, Compensation = ShortageCount * K (where K is a preset gain coefficient). This is equivalent to the integral term in a PID controller, which can gradually eliminate continuous prediction bias and ensure that quota supply gradually approaches actual demand. Finally, the quota shortage event is used to back-optimize the prediction engine and adjust the resource quota calculation formula.
[0074] This application also discloses a Java memory leak detection system based on bytecode enhancement. (See also...) Figure 2 ,include: The non-intrusive probe module 201 is used to monitor the creation of objects of a specified class in a non-intrusive manner within a Java application. It records the lifecycle information of the monitored objects based on weak reference technology and generates raw statistical data. The monitored objects refer to objects of the specified class being monitored. The intelligent analysis engine module 202 is used to periodically acquire the raw statistical data in an analysis service independent of the Java application, and perform multi-dimensional correlation analysis on the raw statistical data; wherein, the multi-dimensional analysis includes at least a quantitative dimension analysis of the growth rate of the number of monitored objects and a time dimension analysis based on the survival time of the monitored objects; The fusion decision and alarm module 203 is used to make a fusion judgment on whether a memory leak has occurred based on the results of multi-dimensional correlation analysis, and to trigger the output of corresponding alarm information when any risk condition is met, so that the administrator can be informed.
[0075] Optionally, the non-intrusive probe module 201 is used to create a weak reference to the monitored object when the monitored object is detected to be created, and associate the currently created weak reference with a reference queue managed by the reclaimer; at the same time, it creates tracking information metadata containing the creation timestamp of the monitored object, and associates and stores the weak reference with the tracking information metadata; it is also used to continuously monitor the reference queue, and when a weak reference created before the current time is captured in the reference queue, it is considered that the monitored object corresponding to the captured weak reference has been reclaimed by the reclaimer. At this time, the association between the captured weak reference and the corresponding tracking information metadata is released, and the original statistical data is updated; wherein, monitored objects that have not been reclaimed by the reclaimer are considered to be in a live state, and the original statistical data includes: the number of live monitored objects in each specified class, and the set of creation timestamps of live monitored objects.
[0076] Optionally, the fusion decision and alarm module 203 is further configured to trigger a growth rate abnormality alarm when the quantitative dimension analysis of the growth rate of the monitored objects indicates that the growth rate of the monitored objects of the target class exceeds a preset first threshold; and output the triggered growth rate abnormality alarm information; wherein, the target class refers to any specified class; when the time dimension analysis based on the survival time of the monitored objects indicates that the number of monitored objects with extremely long survival times among the monitored objects of the target class exceeds a preset second threshold, trigger an extremely long survival abnormality alarm and output extremely long survival abnormality alarm information; further configured to trigger a memory trend abnormality alarm and output a memory trend abnormality alarm when the memory dimension analysis based on the JVM heap memory usage trend indicates that the JVM heap memory is showing a continuous upward trend; when the growth rate abnormality alarm, the extremely long survival abnormality alarm and the memory trend abnormality alarm are triggered simultaneously for the monitored objects of the same target class, it is determined that the target class has a memory leak, and a memory leak alarm information is triggered and output.
[0077] Optionally, the fusion decision and alarm module 203 is also used to establish a corresponding monitoring object survival time model based on historical data for each specified class based on a preset model; to predict the expected recycling time limit of the monitoring object of the target class using the monitoring object survival time model corresponding to the target class; and to use the preset recycling time limit as a third threshold for determining whether the monitoring object of the target class has an excessively long survival time.
[0078] Optionally, it also includes a weak reference reuse module, used to initialize and maintain a global weak reference object pool to store reusable weak reference instances, while continuously monitoring and counting the creation frequency of objects of different specified classes; based on the creation frequency of each specified class object, a prediction engine is established for each specified class, and the prediction engine is used to predict the expected number of objects created for the corresponding specified class in a future time window; according to the expected number of objects created for each specified class and the corresponding preset monitoring priority, the weak reference resource quota for each specified class is dynamically calculated; wherein, the higher the monitoring priority, the larger the corresponding weak reference resource quota, that is, the larger the number of weak reference instances available for allocation; The non-intrusive probe module 201 is used to allocate a weak reference instance from the weak reference object pool to reference the currently created monitoring object and update the current weak reference resource quota of the specified class to which the currently created monitoring object belongs when and only when the current weak reference resource quota of the specified class to which the currently created monitoring object belongs is less than the corresponding weak reference resource quota. It also includes a degradation sampling monitoring module, which is used to implement a sampling monitoring strategy for low-priority specified classes according to the monitoring priority of each specified class when the global resources of the weak reference object pool are detected to be strained. The sampling monitoring strategy is used to reduce the number of weak reference instances allocated from the weak reference object pool to low-priority specified class objects.
[0079] Optionally, the degradation sampling monitoring module is also used to set the low-priority designated classes of the real-time sampling monitoring strategy as degradation classes, and set a sampling rate for each degradation class; according to the sampling rate, by random sampling, some newly created objects in the degradation class are used as monitoring objects, weak reference instances are allocated and tracking information metadata is created; based on the tracking metadata corresponding to the monitoring objects of the degradation class and the life cycle status of the allocated weak reference instances, multi-dimensional correlation analysis is performed on the monitoring objects of the degradation class.
[0080] Optionally, it also includes an adaptive feedback adjustment module, which generates and records a quota shortage event whenever the current weak reference resource used quota of the specified class to which the currently created monitoring object belongs is greater than or equal to the corresponding weak reference resource quota; periodically monitors and statistically analyzes the quota shortage events recorded for different specified classes, and calibrates and optimizes the prediction engine based on the analysis of the quota shortage events.
[0081] This application also discloses a Java memory leak detection device based on bytecode enhancement. The Java memory leak detection device based on bytecode enhancement includes a memory and a processor. The memory stores a computer program that can be loaded by the processor and executed as described above for Java memory leak detection based on bytecode enhancement.
[0082] This application also discloses a computer-readable storage medium that stores a computer program that can be loaded by a processor and executed as described above in the bytecode-enhanced Java memory leak detection method. The computer-readable storage medium includes, for example, various media capable of storing program code, such as a USB flash drive, a portable hard drive, a read-only memory (ROM), a random access memory (RAM), a magnetic disk, or an optical disk.
[0083] It should be noted that in this paper, relational terms such as first and second are used only to distinguish one entity or operation from another entity or operation, and do not necessarily require or imply any such actual relationship or order between these entities or operations.
[0084] The above embodiments are only used to illustrate the technical solutions of this application, and are not intended to limit the scope of protection of the application. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. Based on these embodiments, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.
Claims
1. A bytecode enhancement based Java memory leak detection method, characterized in that, The application comprises the following steps: In the Java application, the object creation of the specified class is monitored in a non-intrusive manner, the life cycle information of the monitoring object is recorded based on the weak reference technology, and the original statistical data is generated; wherein the monitoring object refers to the object of the specified class to be monitored; In the analysis service independent of the Java application, the original statistical data is acquired at a fixed time, and multi-dimensional correlation analysis is performed on the original statistical data; wherein the multi-dimensional analysis at least includes the number dimension analysis of the monitoring object number growth rate, and the time dimension analysis based on the monitoring object survival duration; According to the multi-dimensional correlation analysis result, it is determined whether memory leakage occurs, and when any risk condition is met, the corresponding alarm information is triggered and outputted for the administrator to know.
2. The bytecode enhancement based Java memory leak detection method of claim 1, wherein, The life cycle information comprises the created timestamp of the monitoring object; The life cycle information of the monitoring object is recorded based on the weak reference technology, comprising the following steps: When the monitoring object is created, a weak reference is created to reference the monitoring object, the current created weak reference is associated with a reference queue managed by a garbage collector; at the same time, a tracking information metadata containing the created timestamp of the monitoring object is created, and the weak reference is associated and stored with the tracking information metadata; The reference queue is continuously monitored, and when a weak reference created before the current time is captured in the reference queue, it is considered that the monitoring object corresponding to the captured weak reference has been recycled by the garbage collector, at which time the association between the captured weak reference and the corresponding tracking information metadata is released, and the original statistical data is updated; wherein the monitoring object not recycled by the garbage collector is considered to be in a survival state, and the original statistical data comprises the number of monitoring objects in a survival state and the created timestamp set of the monitoring objects in a survival state of the current monitoring objects of each specified class.
3. The bytecode enhancement based Java memory leak detection method of claim 1, wherein, The multi-dimensional correlation analysis further comprises memory dimension analysis based on the JVM heap memory usage trend; According to the multi-dimensional correlation analysis result, it is determined whether memory leakage occurs, and when any risk condition is met, the corresponding alarm information is triggered and outputted, comprising the following steps: When the number dimension analysis of the monitoring object number growth rate indicates that the growth rate of the monitoring object of the target class exceeds a preset first threshold, a growth rate abnormal alarm is triggered; the growth rate abnormal alarm information is outputted; wherein the target class refers to any specified class; When the time dimension analysis based on the monitoring object survival duration indicates that the number of monitoring objects with an excessively long survival duration in the monitoring object of the target class exceeds a preset second threshold, an excessively long survival abnormal alarm is triggered, and the excessively long survival abnormal alarm information is outputted; When the memory dimension analysis based on the JVM heap memory usage trend indicates that the JVM heap memory presents a continuous rising trend, a memory trend abnormal alarm is triggered, and the memory trend abnormal alarm information is outputted; When the growth rate abnormal alarm, the excessively long survival abnormal alarm and the memory trend abnormal alarm are simultaneously triggered for the monitoring object of the same target class, it is determined that the target class has memory leakage, and the memory leakage alarm information is triggered and outputted.
4. The bytecode enhancement based Java memory leak detection method of claim 3, wherein, The super-long survival refers to a survival time longer than a preset third threshold value; The fusion judgment of whether the memory leakage occurs according to the multi-dimensional correlation analysis result, and the output of the corresponding alarm information when any risk condition is met according to the preset different risk conditions further comprises: Based on the preset, the corresponding monitoring object survival time model based on historical data is established for each specified class; The expected recycling time limit of the monitoring object of the target class is predicted by using the monitoring object survival time model corresponding to the target class; The preset recycling time limit is used as the third threshold value for judging whether the monitoring object of the target class is super-long survival.
5. The bytecode enhancement based Java memory leak detection method of claim 2, wherein, The method further comprises: Initializing and maintaining a global weak reference object pool for storing reusable weak reference instances, while continuously monitoring and counting the creation frequency of different specified class objects; Based on the creation frequency of each specified class object, a prediction engine is established for each specified class to predict the expected object creation quantity of the corresponding specified class in a future time window by using the prediction engine; According to the expected object creation quantity of each specified class and the corresponding preset monitoring priority, the weak reference resource quota of each specified class is calculated; wherein the higher the monitoring priority, the larger the corresponding weak reference resource quota, that is, the larger the number of weak reference instances available for allocation; The method further comprises: When the global resource of the weak reference object pool is tight, the sampling monitoring strategy is implemented for the low-priority specified class according to the monitoring priority of each specified class; the sampling monitoring strategy is used to reduce the number of weak reference instances allocated from the weak reference object pool to the low-priority specified class object. The sampling monitoring strategy for the low-priority specified class comprises: The low-priority specified class of the real-time sampling monitoring strategy is set as a degraded class, and a sampling rate is set for each degraded class; 6. The bytecode enhancement based Java memory leak detection method of claim 5, wherein, According to the sampling rate, some newly created objects in the degraded class are allocated weak reference instances and create tracking information metadata through random sampling; According to the tracking metadata corresponding to the monitoring object of the degraded class and the life cycle state of the allocated weak reference instance, the monitoring object of the degraded class is subjected to multi-dimensional correlation analysis. The method further comprises: Whenever the current weak reference resource used quota of the specified class to which the currently created monitoring object belongs is greater than or equal to the corresponding weak reference resource quota, a quota shortage event is generated and recorded; 7. The bytecode enhancement based Java memory leak detection method of claim 6, wherein, The quota shortage events corresponding to different specified classes are regularly monitored and counted, and the prediction engine is calibrated and optimized according to the analysis of the quota shortage events. 8. A bytecode enhancement based Java memory leak detection system, characterized in that, The non-invasive probe module (201) is used for monitoring object creation of a specified class in a Java application in a non-invasive manner, recording life cycle information of a monitoring object based on a weak reference technology, and generating original statistical data; wherein the monitoring object refers to an object of the specified class to be monitored; The intelligent analysis engine module (202) is used for acquiring the original statistical data in an analysis service independent of the Java application, performing multi-dimensional correlation analysis on the original statistical data; wherein the multi-dimensional analysis at least includes number dimension analysis of a monitoring object number growth rate, and time dimension analysis based on a monitoring object survival time length; The fusion decision and alarm module (203) is used for performing fusion judgment on whether memory leakage occurs according to the multi-dimensional correlation analysis result, and triggering output of corresponding alarm information when any risk condition is met according to preset different risk conditions, so as to be known by an administrator.
9. An apparatus for detecting memory leaks in Java based on bytecode enhancement, comprising: A memory and a processor are included, and the memory stores a computer program capable of being loaded and executed by the processor to perform the method of any one of claims 1 to 7.
10. A computer-readable storage medium, characterized in that, A memory stores a computer program capable of being loaded and executed by the processor to perform the method of any one of claims 1 to 7.