A cross-thread monitoring method, device and electronic equipment for application performance
By dynamically detecting and configuring update threads, the problem of passing parent-child thread context in distributed systems is solved, realizing automated and non-intrusive cross-thread monitoring, improving tracing efficiency and reducing system overhead.
Patent Information
- Application Number
- CN202510987066.2
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-07-17
- Publication Date
- 2026-02-17
- Estimated Expiration
- 2045-07-17
AI Technical Summary
In distributed systems, existing technologies struggle to effectively track context passing between parent and child threads, leading to increased development complexity and maintenance costs. Furthermore, indiscriminate context associations may introduce performance overhead.
By dynamically detecting cross-thread operations, obtaining the parent-child relationship between threads, and creating a configuration update thread to modify and pass configuration parameters, cross-thread operation tracing logic is injected automatically and non-intrusively, ensuring the integrity and efficiency of context passing.
It improves the efficiency of context tracing in cross-thread operation scenarios, reduces the time the parent thread waits for the child thread, and reduces unnecessary system overhead.
Smart Images

Figure CN120803874B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of computer software technology, and in particular to a method, apparatus, and electronic device for cross-thread monitoring of application performance. Background Technology
[0002] An application is a computer program designed to perform specific tasks, such as e-commerce transactions, social networks, and data analysis. To ensure the normal operation of an application, its performance can be monitored using APM (Application Performance Monitoring). The application's code, services, and data are typically stored across multiple nodes in a distributed system. For example, different services on an e-commerce platform, such as "user service," "order service," and "payment service," are deployed on different servers. Through network communication and collaboration within the distributed system, the application interacts across nodes using the API framework provided by the distributed system.
[0003] However, in distributed systems, especially in multi-threaded environments, each Java thread has its own independent call stack and local variables. This makes it impossible for the parent thread's context to be directly inherited by the child thread. In this case, it is challenging for distributed application performance monitoring solutions to track the passage of context between parent and child threads.
[0004] To address the challenges of tracking the passage of context between parent and child threads in distributed application performance monitoring solutions, existing technologies typically involve developers manually injecting context tracing code, which undoubtedly increases development complexity and maintenance costs. Summary of the Invention
[0005] In view of this, embodiments of this application provide a method, apparatus, and electronic device for cross-thread monitoring of application performance, so as to achieve automated and non-intrusive injection of cross-thread operation tracing logic and improve the efficiency of tracing context transmission.
[0006] In a first aspect, embodiments of this application provide a cross-thread monitoring method for application performance, wherein the method includes:
[0007] Execute a performance monitoring task for the target application and dynamically detect whether cross-thread operations exist during the execution of the target application performance monitoring task.
[0008] If the cross-thread operation exists, obtain the parent-child relationship between threads and determine whether there is a target parent thread that needs to wait for the child thread;
[0009] If the target parent thread exists, a configuration update thread is created, and the transfer configuration parameter between the target parent thread and the child thread is modified through the configuration update thread, so that the target parent thread determines whether to transfer the trace context to the child thread based on the transfer configuration parameter.
[0010] In a second aspect, the embodiments of the present application provide a cross-thread monitoring device for application performance, and the device comprises:
[0011] The detection module is configured to perform a target application performance monitoring task, and dynamically detect whether a cross-thread operation exists in a process of executing the target application performance monitoring task.
[0012] The thread analysis module is configured to, if the cross-thread operation exists, acquire a parent-child relationship between threads, and determine whether a target parent thread that needs to wait for a child thread exists.
[0013] The configuration update module is configured to, if the target parent thread exists, create a configuration update thread, and modify a transfer configuration parameter between the target parent thread and the child thread through the configuration update thread, so that the target parent thread determines whether to transfer the trace context to the child thread based on the transfer configuration parameter.
[0014] In a third aspect, the embodiments of the present application provide an electronic device, which comprises a processor and a memory storing a program, wherein the program comprises instructions which, when executed by the processor, cause the processor to perform the cross-thread monitoring method for application performance.
[0015] In a fourth aspect, the embodiments of the present application provide a non-transitory computer-readable storage medium storing computer instructions, wherein the computer instructions are used to cause a computer to perform the cross-thread monitoring method for application performance.
[0016] The embodiments of the present application have the following beneficial effects:
[0017] The application provides a cross-thread monitoring method and device for application performance and an electronic device. When a target application performance monitoring task is executed, whether there is a cross-thread operation in the execution process of the target application performance monitoring task is dynamically detected. If there is a cross-thread operation, the parent-child relationship between threads is further acquired. If there is a parent thread that needs to wait for a child thread, a configuration updating thread is created, and the transmission configuration parameter between the parent thread and the child thread is modified through the configuration updating thread, so that the parent thread determines whether the tracking context needs to be transmitted to the child thread based on the transmission configuration parameter. In this way, the transmission of the tracking context is upgraded from static configuration to dynamic configuration, the cross-thread operation tracking logic is automatically and non-invasively injected, the integrity of the tracking context in the cross-thread operation scenario is guaranteed, the efficiency of the tracking context transmission is improved, the time length of the parent thread waiting for the child thread is reduced, and the system invalid overhead is reduced. BRIEF DESCRIPTION OF DRAWINGS
[0018] In the following description of the example embodiments in conjunction with the attached drawings, more details, features and advantages of the application are disclosed, in which:
[0019] Figure 1 A flowchart of a cross-thread monitoring method for application performance provided by an embodiment of the application is shown;
[0020] Figure 2 Another flowchart of a cross-thread monitoring method for application performance provided by an embodiment of the application is shown;
[0021] Figure 3 A structure diagram of a cross-thread monitoring device for application performance provided by an embodiment of the application is shown;
[0022] Figure 4 A structure block diagram of an example electronic device capable of implementing an embodiment of the application is shown. DETAILED DESCRIPTION
[0023] Embodiments of the application will be described in more detail below with reference to the accompanying drawings. Although some embodiments of the application are shown in the drawings, it should be understood that the application can be implemented in various forms, and should not be interpreted as being limited to the embodiments set forth herein, but rather, these embodiments are provided to more thoroughly and completely understand the application. It should be understood that the drawings and embodiments of the application are only for exemplary purposes, and are not intended to limit the scope of protection of the application.
[0024] It should be understood that each step described in the method embodiments of the application can be executed in different orders and / or in parallel. In addition, the method embodiments can include additional steps and / or omit the execution of the steps shown. The scope of the application is not limited in this respect.
[0025] The term “include” and variations thereof as used herein mean “to include, without limitation.” The term “based on” means “based at least in part on.” The term “one embodiment” means “at least one embodiment.” The term “another embodiment” means “at least one additional embodiment.” The term “some embodiments” means “at least some embodiments.” Related terms shall be construed accordingly. It should be noted that “first,” “second,” and / or the like are only used to differentiate one implementation from another, and do not imply an order of importance or dependency, unless otherwise indicated.
[0026] It should be noted that the terms “a” and “an” and “the” and “at least one” and “one or more” are open-ended terms, and thus should be affi rmed to mean that “one or more” unless otherwise noted. It should be noted that the terms “first,” “second,” and the like can be used herein to describe various elements in an example embodiment, and the elements should not be limited by these terms.
[0027] With the wide application of distributed systems and microservice frameworks, APM has become an important means to ensure system performance and reliability. Among them, the common distributed tracking scheme is based on OpenTracing implementation. OpenTracing is a set of standardized specifications for distributed system tracking, which is used to unify the API and data model of different distributed tracking systems, and helps developers to implement end-to-end performance monitoring in microservice architecture. Among them, OpenTracing mainly records the propagation path (also known as the propagation chain) of the request in the system through Span and Trace. Specifically, the OpenTracing performance monitoring workflow can include:
[0028] 1. Data collection: Buried points and create Spans in the code. Span can be understood as a span, which represents an independent unit of work of OpenTracing, such as a function call or a database query. The data associated with it includes: operation name, start / end time, duration, label, log, reference, label is used to record business attributes, log is used to record key events (such as error information), and reference is used to associate other Spans (such as child Span relationship).
[0029] 2. Cross-service tracking: Write Span Context into the data packet header, such as HTTP Header. The downstream service creates a child Span by parsing the data packet header and then obtains the entire tracking chain by carrying the Span Context in the message data packet header in the message queue, such as the Kafka queue. Among them, all related Spans can be linked by TraceID, and then a complete user request link can be recorded through a tree structure, such as the whole process from the front-end request to the back-end microservice.
[0030] Wherein, the Span Context can be referred to as a span context, and can also be referred to as a trace context, that is, in the present application, the trace context is a noun, rather than a verb. The content of the trace context can include trace metadata such as TraceID, Span ID, and the Span Context is a carrier of various trace metadata, used to pass trace information between services, wherein the spans of different services in the distributed system can be associated with the same trace, such as through HTTP packet header Header, message queue attribute transmission, and the like.
[0031] 3. Data aggregation and storage: receiving a Span data source and storing it in a corresponding database.
[0032] 4. Performance analysis and visualization: the complete request chain generated by the user can be retrieved from the database through the TraceID, and then the time consumption proportion of each Span is analyzed to locate the existing problems, such as slow database query, service call delay, etc. Performance indicators such as overall service response time, call frequency and error rate of each microservice, resource consumption, etc. are generated according to the analysis results.
[0033] In summary, in the distributed tracking process, it is necessary to ensure that the trace context of the parent thread can be inherited by the child thread (such as the Trace ID and Span ID of the parent thread need to be passed to the child thread) to form a complete call chain. After the child thread is executed, the completion time of the Span can be correctly recorded and associated with the parent Span.
[0034] However, the transfer of the trace context (such as the aforementioned Span Context in OpenTracing) between parent and child threads is challenging. For example, when using Java's ThreadPoolExecutor or New Thread to create a thread, it is difficult to pass the trace context between the parent and child threads. This is mainly reflected in the asynchronous nature of thread scheduling and the thread isolation of context storage, which is embodied in the following aspects:
[0035] 1) Each Java thread has an independent call stack (Call Stack) and local variables, and the trace context of the parent thread cannot be inherited by the child thread by default.
[0036] 2) The child thread created by the ThreadPoolExecutor thread pool can be scheduled by different thread executors, and the execution time and thread are not determined.
[0037] This leads to: ThreadLocal is thread isolated, and child threads cannot obtain the ThreadLocal value of the parent thread; secondly, the threads in the thread pool are reused, and the original trace context may have been lost when executing tasks; or when asynchronous callbacks, such as in asynchronous change models such as CompletableFuture, the callback function may be executed on a different thread, resulting in the loss of the trace context. In order to overcome such problems, the prior art usually requires the developer to manually inject the trace code, increasing the development complexity and maintenance cost.
[0038] In addition to the above-mentioned prior art of increasing development complexity and maintenance cost by manually injecting the trace code by the developer, the manual injection of the trace code requires that the trace context of the parent thread be passed to the child thread regardless of whether the child thread task needs to be traced, which may introduce unnecessary performance overhead due to indiscriminate context association, especially when the parent thread does not wait for the child thread task to complete, the transfer of the trace context is meaningless and increases performance loss.
[0039] On this basis, the prior art proposes that the JavaAgent technology can be used to dynamically modify the bytecode when the Java virtual machine (JVM) loads the class, which provides the possibility of automatically injecting the trace context for the trace logic. However, this scheme still has the following problems: it is difficult to generate a semantically rich code representation by directly parsing the bytecode, so it is challenging to analyze whether the parent thread waits for the child thread task under complex synchronization scenarios such as Future transfer and CountDownLatch, and lacks asynchronous analysis and decompilation mechanisms, resulting in the inability to flexibly adjust the corresponding trace strategy in actual application processes.
[0040] Therefore, the present application provides a cross-thread monitoring method, device and electronic equipment for application program performance. In a first aspect, the present application provides a cross-thread monitoring method for application program performance. The method is applied to any electronic device with cross-thread monitoring function for application program performance, including but not limited to personal mobile terminal, computer or server, etc. As shown in the figure, the method comprises the following steps: Figure 1
[0041] S11, execute a target application performance monitoring task, and dynamically detect whether there is a cross-thread operation in the execution process of the target application performance monitoring task;
[0042] S12, if the cross-thread operation exists, obtain the parent-child relationship between threads, and determine whether there is a target parent thread that needs to wait for a child thread;
[0043] S13, if the target parent thread exists, create a configuration update thread, and modify the transfer configuration parameter between the target parent thread and the child thread through the configuration update thread, so that the target parent thread determines whether to transfer the trace context to the child thread based on the transfer configuration parameter.
[0044] The method provided in the application upgrades the transfer of the trace context from static configuration to dynamic configuration by dynamically detecting whether there is a cross-thread operation in the execution process of the target application performance monitoring task when performing the target application performance monitoring task, further obtaining the parent-child relationship between threads if there is a cross-thread operation, creating a configuration update thread and modifying the transfer configuration parameter between the parent thread and the child thread through the configuration update thread if there is a parent thread that needs to wait for a child thread, so that the parent thread determines whether to transfer the trace context to the child thread based on the transfer configuration parameter. In this way, the transfer of the trace context is upgraded from static configuration to dynamic configuration, which realizes automatic and non-invasive injection of cross-thread operation tracking logic, guarantees the integrity of the trace context in the cross-thread operation scenario, improves the efficiency of the transfer of the trace context, reduces the time length of the parent thread waiting for the child thread, and reduces the invalid overhead of the system.
[0045] The above steps S11 to S13 will be described in detail below in conjunction with specific examples:
[0046] In the application, the target application performance monitoring task can be an APM task developed by a developer as needed in advance, and the application performance is monitored by executing the APM task. Specifically, the distributed tracking association of the cross-thread operation is realized through the APM task. As an example, the target application performance monitoring task is the monitoring task submitted by the ThreadPoolExecutor in the Java application or the monitoring task constructed by new Thread in the Java application under the OpenTracing specification mentioned above, and the distributed tracking association of the cross-thread operation is realized through the monitoring tasks.
[0047] Further, the target application performance monitoring task refers to a business execution unit implemented by the ThreadPoolExecutor or created by the new Thread and implementing the Runnable or Callable interface, and the cross-thread monitoring of the application performance is implemented through the business execution unit. That is, in the present application, the execution step S11 executes the target application performance monitoring task, which can be the business execution unit implemented by the ThreadPoolExecutor or created by the new Thread and implementing the Runnable or Callable interface. Among them, the ThreadPoolExecutor is a core class for implementing a thread pool in the Java standard library, and in this paper, the ThreadPoolExecutor is referred to as a preset thread core class. By reusing thread resources, managing thread life cycles, and controlling development degrees, the performance and stability of multi-threaded applications are ensured. In other words, the business execution unit created by the ThreadPoolExecutor needs to meet the task parameters and task execution logic rules set by the ThreadPoolExecutor to be normally executed.
[0048] In order to be able to dynamically detect whether the target application performance monitoring task has cross-thread operation, the present application modifies the task execution logic rules set in the ThreadPoolExecutor, especially modifies the task detection rules, so that the task created by the ThreadPoolExecutor supports cross-thread operation and supports dynamic detection of the task. Based on this, in some possible embodiments, before the execution step S11, the method further includes the following steps S10-1 and S10-2 to modify the task detection rules of the ThreadPoolExecutor:
[0049] S10-1, in response to the JavaAgent startup operation in the virtual machine, dynamically modifying the bytecode of the thread startup method and / or the thread running method in the preset thread core class, and adding dynamic detection execution logic in the execution logic of the thread startup method and / or the thread running method;
[0050] S10-2, executing the thread startup method or the thread running method, dynamically detecting the target application performance monitoring task, and determining whether there is cross-thread operation in the execution process of the target application performance monitoring task.
[0051] Wherein, the virtual machine is a Java virtual machine JVM, and the JavaAgent is a special Jar file in Java, which is a bytecode enhancement technology and allows Java programs to modify or monitor Java classes in the code during program execution. In step S10-1, if the JavaAgent in the JVM is started, the thread starting method and / or the thread running method in the preset thread core class can be modified through the JavaAgent. Wherein, the preset thread core class can be the ThreadPoolExecutor described above, or the Thread class, the thread starting method in the preset thread core class can be the submit method in the ThreadPoolExecutor, and the thread running method in the preset thread core class can be the execute method in the ThreadPoolExecutor.
[0052] Therefore, as an embodiment, when performing the above step S10-1, the ASM (a Java bytecode operation framework) or ByteBuddy (another Java bytecode operation framework) framework can be used to modify the submit and execute methods of the ThreadPoolExecutor and / or the constructor method (such as Thread(Runnable) and run method) of the Thread class through the JavaAgent at the JVM startup, so as to modify the execution logic of the ThreadPoolExecutor and / or the Thread class, and add a dynamic detection execution logic in the execution logic of the thread starting method and / or the thread running method.
[0053] Wherein, the dynamic detection execution logic is set according to actual needs, and as an embodiment, the dynamic detection execution logic can be simply divided into: intercepting the task submission of the target application performance monitoring task, intercepting the task execution of the target application performance monitoring task, detecting cross-thread operation, and asynchronously uploading files (such as uploading class files abnormally). Wherein, the class file is a Java bytecode file used to store compiled Java classes or interfaces, and in the embodiment of the present application, the class file refers to the file generated after the class implementing the monitoring logic is compiled.
[0054] Specifically, the ASM or ByteBuddy framework can be used to modify the bytecode of the following key methods:
[0055] For the ThreadPoolExecutor.submit(Runnable task) method, the execution logic of intercepting the task submitted by the thread pool is added;
[0056] For the ThreadPoolExecutor.execute(Runnable command) method, the execution logic of intercepting the execution of the task of the thread pool is added;
[0057] For the Thread.start() method, the execution logic of intercepting the start operation of the thread created by new Thread is added;
[0058] For the constructor method (such as Thread(Runnable target)) of the Thread class, the execution logic of capturing the Runnable task instance passed in is added.
[0059] Among them, the newly added execution logic will automatically trigger the capture of the task instance and the cross-thread operation detection when these methods are executed, without the need to modify the business code.
[0060] By selecting the embodiment of the present application, the JavaAgent can dynamically modify the bytecodes of the thread start method and / or the thread running method, so as to achieve the dynamic detection execution logic without modifying the business code, and the dynamic detection execution logic is set without invasion. Since it modifies the class at runtime, it can achieve dynamic modification of the dynamic detection execution logic without restarting the application, and it is suitable for any type of Java application and is not limited by the framework.
[0061] As an implementation mode, the above-mentioned dynamic detection execution logic includes cross-thread operation detection logic, which can be implemented by the following steps when the above-mentioned step S10-2 is executed:
[0062] When the target application performance monitoring task is submitted, the cross-thread operation detection logic is executed to obtain the task instance of the target application performance monitoring task;
[0063] According to the task instance, it is determined whether the target application performance monitoring task has cross-thread operation.
[0064] Among them, the cross-thread operation detection logic specifically includes: a. Obtain the key information of the task instance, wherein the key information of the task instance includes: task object, parent thread context, task class identifier. The task object includes: obtaining the passed-in Runnable or Callable instance, such as task.getClass().getName(). The parent thread context information includes: recording the parent thread information of the currently submitted task, including the thread ID and call stack information of the parent thread. The character class identifier is used as a unique identifier for the class name of the task to distinguish different tasks.
[0065] If the cross-thread operation exists, the target application performance monitoring task is marked as a cross-thread operation task, and is stored in a temporary buffer area, which can be ThreadLocal or a memory queue.
[0066] As another implementation, the parent thread ID can also be obtained by the Thread.getId() method, and compared with the worker thread ID of the thread pool (which can be obtained by getThreadFactory() of the thread pool). If they are consistent, there is no cross-thread operation. If they are inconsistent, there is a cross-thread operation.
[0067] If it is determined that the target application performance monitoring task has a cross-thread operation, the corresponding target application performance monitoring task can be marked as a cross-thread operation task and stored in a temporary buffer area, which can be ThreadLocal or a memory queue.
[0068] On the basis of determining that there is a cross-thread operation in step S11, the method provided by the application further comprises:
[0069] S2, if the cross-thread operation exists, triggering an asynchronous analysis process, wherein the asynchronous analysis process comprises:
[0070] S21, asynchronously uploading the class file corresponding to the target application performance monitoring task to a backend server, and generating source code based on the class file by using a decompilation tool of the backend server;
[0071] S22, calling each middleware in the large language model intelligent component to analyze the source code, and obtaining the parent-child relationship between threads and determining whether there is a target parent thread that needs to wait for a child thread.
[0072] The asynchronous analysis process can be subdivided into: task class file acquisition, asynchronous upload, source code analysis. Among them, when executing the above step S21, the Instrumentation API interface provided by JavaAgent can be used to extract the class byte stream of the task instance, and then the corresponding class file is generated based on the calss byte stream. Specifically, the class byte stream, task class name, parent thread call stack information and other information can be summarized and sorted to generate a class file. Further, through the HTTP Hypertext Transfer Protocol or message queue (such as Kafka queue), an asynchronous upload method is used to upload the class file to the server in the back end. In this way, the class file upload thread can be avoided to block the business thread.
[0073] Further, the class file is decompiled into Java source code by the backend server using a decompilation tool. Among them, the backend server can use Fernflower (a decompilation tool) or CFR (another decompilation tool) to decompile the class file into Java source code. Then, the class name, method signature, field information and the like related to the target application performance monitoring task in the source code are extracted, and a JSON format structured representation is generated, so as to execute step S12 or step S22, based on the JSON format structured representation, to obtain the parent-child relationship between threads and determine whether there is a target parent thread that needs to wait for a child thread.
[0074] Specifically, information extraction can be performed on the structured representation (which can also be understood as structured data), and key information related to thread call association is extracted from the structured data: synchronization method call situation, thread pool usage situation, context transfer situation. Among them, the synchronization method call situation can be obtained by identifying Future.get(), CountDownLatch.await() and other synchronization operations, the thread pool usage situation can be obtained by detecting ExecutorService.submit() and other thread pool submission methods, and the context transfer situation can be obtained by checking ThreadLocal, InheritableThreadLocal and other context transfer tools.
[0075] Specifically, by executing the above step S22, the parent-child relationship between threads and whether there is a target parent thread that needs to wait for a child thread can be obtained by calling each middleware in the large language model intelligent component to analyze the source code or analyze the structured data. Among them, the large language model is referred to as LLM (Large Language Model, large language model LLM), such as GPT-4, and the large language model intelligent component refers to a component developed based on the LLM model and having source code analysis capability.
[0076] As an implementation, the large language model intelligent component can include several intermediates, each of which analyzes the source code, wherein each intermediate can include: code extraction middleware (hereinafter referred to as code extraction Agent), semantic analysis middleware (hereinafter referred to as semantic analysis Agent), synchronous pattern recognition middleware (hereinafter referred to as synchronous pattern recognition Agent), decision middleware (hereinafter referred to as decision Agent). By code extraction, source code analysis of each intermediate to the class file, the parent-child relationship between threads of the target application performance monitoring task can be determined, and whether there is a target parent thread that needs to wait for a child thread.
[0077] Specifically, the input of the code extraction middleware is: the class name of the task object (such as Runnable or Callable), and the call stack of the parent thread. The proxy extraction middleware is configured to obtain the class file, upload the class file to the backend server for decompilation, generate a structured code representation from the backend server, then obtain the readable Java source code from the backend server, and finally output the structured code representation of the target application performance monitoring task. The specific output is the decompiled source code, method signature, and call stack information. As an implementation, the code extraction middleware can output the entire code extraction process through the large language model to set the output format, for example, the code extraction process corresponding to the code extraction middleware can be output in the following format:
[0078] **Task**: Decompile the uploaded class file into Java source code and generate a structured representation.
[0079] **Input**:
[0080] - class file byte stream: {class_file_bytes}
[0081] - Call stack information: {call_stack}
[0082] **Instructions**:
[0083] 1. Use a decompilation tool (such as Fernflower or CFR) to convert the class file into Java source code.
[0084] 2. Extract the class name, method signature, and method body from the source code.
[0085] 3. Combine the call stack information to generate a structured JSON representation in the following format:
[0086] {
[0087] "class_name": "<class_name>",
[0088] "methods": [
[0089] {
[0090] "signature": "<method_signature>",
[0091] "body": "<method_body_source_code>"
[0092] }
[0093] ],
[0094] "call_stack": "<call_stack_info>"
[0095] }
[0096] **Output**:
[0097] - Structured JSON representation containing the decompiled source code and call stack information.
[0098] Further, a semantic analysis Agent is utilized to extract information from the decompiled source code, including method calls, variable passing, and control flow information. Based on the extracted content, a semantic context is constructed to provide a foundation for subsequent synchronization pattern recognition Agents.
[0099] The input for the semantic analysis Agent is the structured code representation generated by the code extraction Agent, which includes the source code and call stack.
[0100] The specific execution process of the semantic analysis Agent includes:
[0101] 1) Use LLM (Transformer-based code analysis model) to parse the decompiled source code.
[0102] 2) Identify method call chains and track the definition, assignment, and passing paths of variables such as Future and CountDownLatch.
[0103] 3) Analyze the control flow to detect conditional branches, loops, and exception handling structures.
[0104] 4) Pay special attention to the passing of Future objects (such as passing to the upper-level caller through return values or parameters).
[0105] 5) Generate semantic context describing the logical structure and dependencies of the code.
[0106] The final output of the semantic analysis agent is a semantic context that includes method call chains, variable flow, and control flow graphs. This semantic context can be represented in JSON or AST format.
[0107] As an implementation, the semantic analysis middleware can output the entire semantic analysis process through a large language model to set the output format. For example, the semantic analysis middleware corresponding to the semantic analysis process can output the following format:
[0108] **Task**: Parse Java source code and extract method calls, variable passing, and control flow information to generate a semantic context.
[0109] **Input**:
[0110] - Structured code representation:
[0111] {
[0112] "class_name": "<class_name>",
[0113] "methods": [
[0114] {
[0115] "signature": "<method_signature>",
[0116] "body": "<method_body_source_code>"
[0117] }
[0118] ],
[0119] "call_stack": "<call_stack_info>"
[0120] }
[0121] **Instructions**:
[0122] 1. Parse the source code and identify all method calls, including method names, parameters, and return values.
[0123] 2. Track the definition, assignment, and passing path of variables such as Future, CountDownLatch.
[0124] 3. Analyze the control flow and identify conditional branches, loops, and exception handling structures.
[0125] 4. Generate semantic context, formatted as follows:
[0126] {
[0127] "method_calls": [
[0128] {
[0129] "method_name": " <name>",
[0130] "parameters": [" <param1> ", " <param2>],
[0131] "return_type": " <type>",
[0132] "caller": "<caller_method>"
[0133] }
[0134] ],
[0135] "variable_flows": [
[0136] {
[0137] "variable_name": " <name>",
[0138] "type": " <type>",
[0139] "definition": "<line_number>",
[0140] "passes_to": ["<method_or_class>"]
[0141] }
[0142] ],
[0143] "control_flow": {
[0144] "branches": [" <condition1> ", " <condition2>],
[0145] "loops": [" <loop1> ", " <loop2>
[0146] }
[0147] }
[0148] **Output**:
[0149] - Semantic context JSON containing method call chains, variable flow, and control flow information.
[0150] Further, the synchronization pattern recognition Agent detects whether there is a synchronization pattern in the Java source code, and then determines whether the parent thread is waiting for the child thread task based on the synchronization pattern. Specifically, the input of the synchronization pattern recognition Agent is the semantic context generated by the semantic analysis Agent, and then based on the semantic context, the following processing flow is executed:
[0151] 1) Analyze the semantic context using a pre-trained large language model (LLM) model for Java synchronization patterns.
[0152] 2) Detect direct waiting patterns: such as Future.get(), Thread.join(), CountDownLatch.await().
[0153] 3) Detect indirect waiting patterns, such as passing Future objects to upper-level callers and calling Future.get().
[0154] 4) Detect other synchronization tools, such as CyclicBarrier.await(), Semaphore.acquire().
[0155] 5) Analyze the context of synchronization operations (such as in loops or conditional branches) to ensure accuracy.
[0156] 6) Generate a synchronization pattern report listing all detected synchronization operations and their call paths.
[0157] Among them, the output of the synchronization pattern recognition Agent is: synchronization pattern report, containing the detected synchronization operation and context information.
[0158] As an implementation, the synchronization pattern recognition Agent can output the entire synchronization pattern recognition process through the large language model setting output format, for example, the synchronization pattern recognition process corresponding to the synchronization pattern recognition Agent can be output in the following format:
[0159] **Task**: Detect synchronization patterns in Java code and determine whether the parent thread is waiting for the child thread task.
[0160] **Input**:
[0161] - Semantic context:
[0162] {
[0163] "method_calls": [
[0164] {
[0165] "method_name": " <name>",
[0166] "parameters": [" <param1> ", " <param2>],
[0167] "return_type": " <type>",
[0168] "caller": "<caller_method>"
[0169] }
[0170] ],
[0171] "variable_flows": [
[0172] {
[0173] "variable_name": " <name>",
[0174] "type": " <type>",
[0175] "definition": "<line_number>",
[0176] "passes_to": ["<method_or_class>"]
[0177] }
[0178] ],
[0179] "control_flow": {
[0180] "branches": [" <condition1> ", " <condition2>],
[0181] "loops": [" <loop1> ", " <loop2>"
[0182] }
[0183] }
[0184] **Instructions**:
[0185] 1. Detect synchronization-related method calls such as Future.get(), Thread.join(), CountDownLatch.await(), CyclicBarrier.await(), Semaphore.acquire().
[0186] 2. Analyze the call path of the Future object and check if Future.get() is called in the upper caller.
[0187] 3. Identify the context of the synchronization operation, such as a loop, conditional branch, or invocation within exception handling.
[0188] 4. Generate a synchronization pattern report in the following format:
[0189] {
[0190] "sync_operations": [
[0191] {
[0192] "type": "<Future.get|Thread.join|CountDownLatch.await>",
[0193] "method": "<method_name>",
[0194] "context": "<loop|branch|try-catch>",
[0195] "call_path": "<caller_method_chain>"
[0196] } ]
[0198] }
[0199] **Output**:
[0200] - Synchronization pattern report JSON listing all synchronization operations and their contexts.
[0201] By the decision Agent based on the synchronization pattern report, it is determined whether the parent thread depends on the result of the child thread task, so as to determine whether there is a target parent thread that needs to wait for the child thread. Further, in some possible embodiments, the method provided by the application further comprises:
[0202] If the target parent thread exists, the target parent thread is associated with the target child thread that the target parent thread needs to wait for, and the configuration update thread is executed.
[0203] Specifically, the decision Agent comprehensively analyzes the synchronization pattern report to determine whether the parent thread depends on the result of the child thread task, and decides whether cross-thread context association is needed. The input of the decision Agent is the synchronization pattern report generated by the synchronization pattern recognition Agent, and then it decides whether cross-thread context association is needed by executing the following process:
[0204] 1) Use LLM to comprehensively analyze the synchronization pattern report to evaluate whether the parent thread waits for the child thread task.
[0205] 2) Apply the decision rule: if Future.get(), Thread.join() or CountDownLatch.await() is detected, mark it as direct waiting. If the Future is passed to the upper caller and the Future.get() is called, mark it as indirect waiting. If CountDownLatch.await() is used and the counter is related to the child thread task, mark it as waiting. If there is no synchronization operation or the child thread runs independently, mark it as no association needed.
[0206] 3) Use the reasoning ability of LLM to output the final decision combined with the confidence score (such as based on the context and frequency of synchronization operations).
[0207] 4) Return a Boolean value to decide whether to modify the tracking configuration.
[0208] The decision Agent outputs a Boolean value, which identifies whether the tracking context needs to be associated through different Boolean values. As an example, True can be returned to identify that the tracking context needs to be associated, and False can be returned to identify that the tracking context does not need to be associated.
[0209] As an implementation, the decision Agent can output the entire decision process through a large language model to set the output format. As an example, the decision process corresponding to the decision Agent can be output in the following format:
[0210] **Task**: Integrate the synchronization pattern report to determine whether the parent thread waits for the child thread task and decide whether cross-thread context association is needed.
[0211] **Output**:
[0212] - Sync Pattern Report:
[0213] {
[0214] "sync_operations": [
[0215] {
[0216] "type": "<Future.get|Thread.join|CountDownLatch.await>",
[0217] "method": "<method_name>",
[0218] "context": "<loop|branch|try-catch>",
[0219] "call_path": "<caller_method_chain>"
[0220] } ]
[0222] }
[0223] **Instructions**:
[0224] 1. Analyze the Sync Pattern Report, identifying direct waits (e.g., Future.get(), Thread.join()) and indirect waits (e.g., Future passed to another method that calls Future.get()).
[0225] 2. Evaluate the context of the synchronization operations, checking if they are related to the child thread tasks (e.g., CountDownLatch's counter).
[0226] 3. Apply decision rules:
[0227] - If there are direct or indirect waits, mark as needing association.
[0228] - If there are no synchronization operations or the child thread runs independently, mark as not needing association.
[0229] 4. Calculate a confidence score (0-1) based on the frequency of synchronization operations and the reliability of the context.
[0230] 5. Output a boolean value and the confidence score, formatted as:
[0231] {
[0232] "needs_tracing": <true | false>,
[0233] "confidence": <0.0-1.0>
[0234] }
[0235] **Output**:
[0236] - A JSON object containing a boolean value of whether the association is needed and a confidence score.
[0237] Further, the boolean value and the confidence score output by the decision Agent can represent whether there is a target parent thread and whether the tracing context association needs to be performed for the target parent thread and the corresponding child thread. Based on this, when performing the above step S13, the following steps can be implemented:
[0238] Creating a configuration update thread and starting the configuration update thread to enable the target parent thread to associate with the tracing context of the child thread at the next parent thread task execution.
[0239] If the decision Agent outputs True, specifically needs_tracing=true, a new thread needs to be started to modify the tracing configuration parameters of the target application performance monitoring task. The tracing configuration parameters are located in the global configuration table of the target application performance monitoring task. Modifying the tracing configuration parameters can be setting the tracing flag for the task type of the target application performance monitoring task in the global configuration table. Then the modified tracing configuration parameters are stored in the thread-safe ConcurrentHashMap, and the task class name that needs to be associated is recorded.
[0240] As an implementation, the configuration update thread is configured as an asynchronous thread, so that the tracing configuration parameter update can be executed through an asynchronous thread, which can ensure that the configuration update thread does not block the business main thread of the application.
[0241] In which, enabling the target parent thread to associate with the tracing context of the child thread at the next parent thread task execution includes:
[0242] At the next execution of the target application performance monitoring task, check the global configuration table. If the task class name in the global configuration table has been marked as needing to be associated, serialize the trace context SpanContext into Map format through the Inject method of OpenTracing, and attach it to the custom field of the parent thread task. Further, before the execution of the child thread task, specifically through the execute method or the run method, if the child thread task contains the trace context SpanContext, restore it through the Extract method, create a child Span, and associate the corresponding parent Span.
[0243] Finally, after the execution of the child thread task is completed, collect the Span data, including the execution time and the operation name, and then report the corresponding target application performance monitoring task monitoring of a complete user request link to the OpenTracing compatible trace system (such as Jaeger and Zipkin).
[0244] The following is a code example of a method for implementing the present application, which is only for reference and not as the only implementation code:
[0245] import io.opentracing.SpanContext;
[0246] import java.lang.instrument.Instrumentation;
[0247] import java.util.concurrent.ConcurrentHashMap;
[0248] import java.util.function.Consumer;
[0249] public class CrossThreadTracer {
[0250] private static final ConcurrentHashMap<String, Boolean>traceConfig =new ConcurrentHashMap<>();
[0251] private static Instrumentation instrumentation;
[0252] public static void setInstrumentation(Instrumentation inst) {
[0253] instrumentation = inst;
[0254] }
[0255] public static void interceptSubmit(Runnable task, Tracer tracer) {
[0256] String taskId = task.getClass().getName();
[0257] if (traceConfig.getOrDefault(taskId, false)&&tracer.activeSpan()!=null) {
[0258] Span parentSpan = tracer.activeSpan();
[0259] SpanContext context = parentSpan.context();
[0260] return new TaskWrapper(task, context);
[0261] }
[0262] if (isCrossThreadOperation(task)) {
[0263] LLMAgentPipeline.asyncAnalyzeTask(task, result ->{
[0264] if (result.isParentWaiting()) {
[0265] new Thread(() ->traceConfig.put(taskId, true)).start();
[0266] }
[0267] });
[0268] }
[0269] return task;
[0270] }
[0271] public static void interceptExecute(Runnable task, Tracer tracer) {
[0272] if (task instanceof TaskWrapper) {
[0273] TaskWrapper wrapper = (TaskWrapper) task;
[0274] SpanContext context = wrapper.getContext();
[0275] Span childSpan = tracer.buildSpan("childTask").asChildOf(context).start();
[0276] tracer.scopeManager().activate(childSpan);
[0277] }
[0278] }
[0279] static class LLMAgentPipeline {
[0280] static void asyncAnalyzeTask(Runnable task, Consumer <llmanalysisresult>callback) {
[0281] new Thread(() ->{
[0282] CodeData codeData = CodeExtractionAgent.extract(task);
[0283] SemanticContext context = SemanticAnalysisAgent.analyze(codeData);
[0284] SyncPatterns patterns = SyncPatternAgent.detect(context);
[0285] LLMAnalysisResult result = DecisionAgent.decide(patterns);
[0286] callback.accept(result);
[0287] }).start();
[0288] }
[0289] }
[0290] static class CodeExtractionAgent {
[0291] static CodeData extract(Runnable task) {
[0292] Class<?>taskClass = task.getClass();
[0293] byte[] classFile = getClassFile(taskClass);
[0294] String sourceCode = BackendService.uploadAndDecompile(classFile);
[0295] String callStack = getCallStack();
[0296] return new CodeData(sourceCode, callStack);
[0297] }
[0298] private static byte[] getClassFile(Class<?> clazz) {
[0299] try {
[0300] String className = clazz.getName().replace('.', ' / ');
[0301] return instrumentation.getClassFile(className);
[0302] } catch (Exception e) {
[0303] throw new RuntimeException("Failed to get class file", e);
[0304] }
[0305] }
[0306] private static String getCallStack() {
[0307] return Thread.currentThread().getStackTrace().toString();
[0308] }
[0309] }
[0310] static class SemanticAnalysisAgent {
[0311] static SemanticContext analyze(CodeData codeData) {
[0312] String prompt = String.format(
[0313] Task: Parse Java source code, extract method call, variable passing, and control flow information, and generate a semantic context.
[0314] "Input:\n" +
[0315] "- Structured code representation:\n" +
[0316] "{\n" +
[0317] "\"class_name\": \"%s\",\n" +
[0318] "\"source_code\": \"%s\",\n" +
[0319] "\"call_stack\": \"%s\"\n" +
[0320] "}\n" +
[0321] "Instructions:\n" +
[0322] "1. Parse the source code, identifying all method calls, including method names, arguments, and return values.\n" +
[0323] "2. Trace variable (e.g., Future, CountDownLatch) definitions, assignments, and passing paths.\n" +
[0324] "3. Analyze the control flow, identifying conditional branches, loops, and exception handling structures.\n" +
[0325] "4. Generate the semantic context, formatted as follows:\n" +
[0326] "{\n" +
[0327] "\"method_calls\": [{\"method_name\": " <name>\", \"parameters\": [\" <param1>"], "return_type": " <type>\", \"caller\": \"<caller_method>\"}],\n" +
[0328] "\"variable_flows\": [{\"variable_name\": \" <name>\", \"type\": \" <type>\"\", \"definition\": \"<line_number>\", \"passes_to\": [\"<method_or_class>\"]}]},\n" +
[0329] "\"control_flow\": {\"branches\": [\" <condition1>"], "loops": [ <loop1>"]}\n" +
[0330] "}\n" +
[0331] "Output:\n" +
[0332] "- Semantic context JSON containing method call chain, variable flow, and control flow information.",
[0333] codeData.getClassName(), codeData.getSourceCode(),codeData.getCallStack() );
[0335] return BackendService.callLLM(prompt, SemanticContext.class);
[0336] }
[0337] }
[0338] static class SyncPatternAgent {
[0339] static SyncPatterns detect(SemanticContext context) {
[0340] String prompt = String.format(
[0341] "Task: Detect synchronization patterns in Java code and determine if parent threads are waiting for child thread tasks.\n" +
[0342] "Input:\n" +
[0343] "- Semantic context:\n" +
[0344] "%s\n" +
[0345] "Instructions:\n" +
[0346] "1. Detect synchronization-related method calls such as Future.get(), Thread.join(), CountDownLatch.await(), CyclicBarrier.await(), Semaphore.acquire().\n" +
[0347] "2. Analyze the Future object's call path to check if Future.get() is called in the upper caller.\n" +
[0348] "3. Identify the context of the synchronization operation, such as a loop, conditional branch, or call in exception handling.\n" +
[0349] "4. Generate a synchronization pattern report in the following format:\n" +
[0350] "{\n" +
[0351] "\"sync_operations\": [{\"type\": \"<Future.get|Thread.join|CountDownLatch.await>\", \"method\": \"<method_name>\", \"context\": \"<loop|branch|try-catch>\", \"call_path\": \"<caller_method_chain>\"}]\n" +
[0352] "}\n" +
[0353] "Output:\n" +
[0354] "- Synchronization pattern report JSON listing all synchronization operations and their contexts.",
[0355] context.toJson() );
[0357] return BackendService.callLLM(prompt, SyncPatterns.class);
[0358] }
[0359] }
[0360] static class DecisionAgent {
[0361] static LLMAnalysisResult decide(SyncPatterns patterns) {
[0362] String prompt = String.format(
[0363] "Task: Consolidate synchronization patterns report, determine if parent thread is waiting on child thread tasks, decide if cross-thread context association is needed.\n" +
[0364] "Input:\n" +
[0365] "- Synchronization patterns report:\n" +
[0366] "%s\n" +
[0367] "Instructions:\n" +
[0368] "1. Analyze synchronization patterns report, identify direct waits (e.g. Future.get(), Thread.join()) and indirect waits (e.g. Future passed to another method that calls Future.get()).\n" +
[0369] "2. Evaluate context of synchronization operations, check if related to child thread tasks (e.g. CountDownLatch's counter).\n" +
[0370] "3. Apply decision rules:\n" +
[0371] "- If direct or indirect waits exist, mark as needing association.\n" +
[0372] "- If no synchronization operations or child threads run independently, mark as not needing association.\n" +
[0373] "4. Calculate confidence score (0-1) based on frequency of synchronization operations and context reliability.\n" +
[0374] "5. Output boolean and confidence, format as follows:\n" +
[0375] "{\n" +
[0376] "\"needs_tracing\":<true|false>,\n" +
[0377] "\"confidence\":<0.0-1.0>\n" +
[0378] "}\n" +
[0379] "Output:\n" +
[0380] "- JSON object containing boolean of whether association is needed and confidence score.",
[0381] patterns.toJson() );
[0383] return BackendService.callLLM(prompt, LLMAnalysisResult.class);
[0384] }
[0385] }
[0386] static class LLMAnalysisResult {
[0387] private boolean needsTracing;
[0388] private double confidence;
[0389] boolean isParentWaiting() {
[0390] return needsTracing;
[0391] }
[0392] }
[0393] static class CodeData {
[0394] private String sourceCode;
[0395] private String callStack;
[0396] CodeData(String sourceCode, String callStack) {
[0397] this.sourceCode = sourceCode;
[0398] this.callStack = callStack;
[0399] }
[0400] String getClassName() { return "TaskClass";} / / Simplified
[0401] String getSourceCode() { return sourceCode;}
[0402] String getCallStack() { return callStack;}
[0403] }
[0404] static class SemanticContext {
[0405] String toJson() { return "{}";} / / Simplified
[0406] }
[0407] static class SyncPatterns {
[0408] String toJson() { return "{}";} / / Simplified
[0409] }
[0410] static class BackendService {
[0411] static String uploadAndDecompile(byte[] classFile) {
[0412] String prompt = String.format(
[0413] Task: Decompile the uploaded class files into Java source code and generate a structured representation.\n
[0414] Input:\n" +
[0415] "- class File byte stream: %s\n" +
[0416] "- Call stack information: %s\n" +
[0417] Command:\n" +
[0418] 1. Use a decompiler (such as Fernflower or CFR) to convert the class files into Java source code.
[0419] 2. Extract the class name, method signature, and method body from the source code.
[0420] 3. Combine the call stack information to generate a structured JSON representation, in the following format:\n
[0421] "{\n" +
[0422] "\"class_name\": \"<class_name>\",\n" +
[0423] "\"methods\": [{\"signature\": \"<method_signature>\", \"body\": \"<method_body_source_code>\"}],\n" +
[0424] "\"call_stack\": \"<call_stack_info>\"\n" +
[0425] "}\n" +
[0426] "Output:\n" +
[0427] "- Structured JSON representation containing the decompiled source code and call stack information.",
[0428] Base64.getEncoder().encodeToString(classFile), getCallStack() );
[0430] return callLLM(prompt, String.class);
[0431] }
[0432] static <t>T callLLM(String prompt, Class <t>responseType) {
[0433] / / Simulate LLM call to backend service
[0434] if (responseType == String.class) {
[0435] return (T) " / * Decompiled source code * / ";
[0436] } else if (responseType == SemanticContext.class) {
[0437] return (T) new SemanticContext();
[0438] } else if (responseType == SyncPatterns.class) {
[0439] return (T) new SyncPatterns();
[0440] } else if (responseType == LLMAnalysisResult.class) {
[0441] LLMAnalysisResult result = new LLMAnalysisResult();
[0442] result.needsTracing = true; / / Simplified
[0443] result.confidence = 0.9; / / Simplified
[0444] return (T) result;
[0445] }
[0446] return null;
[0447] }
[0448] private static String getCallStack() {
[0449] return Thread.currentThread().getStackTrace().toString();
[0450] }
[0451] }
[0452] }
[0453] The execution flow diagram of the above code can be referred to the schematic diagram as shown in Figure 2 Before executing the target application performance monitoring task, the dynamic detection logic bytecode is injected in advance, including: injecting the bytecode of ThreadPoolExecute / Thread class in advance, and changing the execution logic of ThreadPoolExecute / Thread. Further, the main thread creates an initial independent work unit Span, further intercepts the task submission of the Span created by the main thread, including two ways of interception: submit or Thread.start interception, and based on the interception result, it is analyzed and detected whether there is cross-thread operation. Wherein, the specific cross-thread operation detection can refer to the related description of the previous step S11, which will not be repeated here. If there is no cross-thread operation, it indicates that the tracking context information does not need to be associated, and the main thread task can be directly continued to be executed without associating the tracking context. If there is cross-thread operation, it indicates that the tracking context needs to be associated.
[0454] Further, the class file of the target application performance monitoring task is obtained by the middleware code extraction Agent in the LLM large language model, and the class file is uploaded to the backend asynchronously, the backend uses a decompilation tool to generate the corresponding source code, and further uses each middleware Agent of LLM to analyze whether the parent thread and the child thread need to be associated, and through the source code analysis as in the above step S22, the parent-child relationship between the threads and the target parent thread that needs to wait for the child thread are determined. If it does not need to be associated, the tasks of the respective threads can be continued to be executed. If it needs to be associated, a configuration update thread is started to modify the tracking configuration parameters, and further, when the next task is executed, the tracking configuration parameters are checked to determine whether the parent-child threads have been started, if not, the tracking context between the two does not need to be associated.
[0455] If enabled, the trace context SpanContext is captured and attached to the task, at which point a child thread is started and the child thread task execution or Thread run is intercepted, the SpanContext is then captured and the corresponding independent unit of work Span is resumed, then a child Span is created, the child thread task is executed by the child Span, and finally the trace data is collected and uploaded to produce the complete request chain generated by the user using the application for analysis of the performance of the application.
[0456] In the embodiments of the present application, cross-thread monitoring can be divided into two categories: cross-thread monitoring of ThreadPoolExecutor task submission and cross-thread monitoring of new Thread construction. Among them:
[0457] The whole process of cross-thread monitoring of ThreadPoolExecutor task submission can be divided into:
[0458] 1. Environment preparation: deploy JavaAgent, configure OpenTracing tracer (such as Jaeger). Inject bytecode in advance for ThreadPoolExecutor's submit and execute methods.
[0459] 2. Task submission: intercept the submit method, detect whether the task is submitted to the thread pool. If cross-thread operation is triggered, use Instrumentation to obtain the class file of the task, and upload it to the backend asynchronously.
[0460] 3. Asynchronous analysis: the backend decompiles the class file into source code, and the LLM Agent analyzes whether the parent thread is waiting for the child thread task (for example, through Future.get() or CountDownLatch.await()).
[0461] 4. Configuration update: if association is needed, start a new thread to update the trace configuration (set the trace flag of the task class name).
[0462] 5. Context association: when the next task is submitted, if the configuration has been updated, capture the SpanContext and attach it to the task. In the execute method, the SpanContext is resumed and a child Span is created.
[0463] 6. Data collection: after the child thread is executed, the trace data is reported through Jaeger.
[0464] The whole process of cross-thread monitoring of new Thread construction can be:
[0465] 1. Environment preparation: Deploy JavaAgent, inject bytecode in advance to the constructor method and run method of Thread class.
[0466] 2. Task submission: Intercept Thread.start, detect cross-thread operations, use Instrumentation to obtain the class file of Runnable, and upload it to the backend asynchronously.
[0467] 3. Asynchronous analysis: The backend decompiles to generate source code, and the LLM Agent analyzes whether the parent thread is waiting for the child thread (for example, through Thread.join()).
[0468] 4. Configuration update: If association is required, start a new thread to update the tracking configuration.
[0469] 5. Context association: When Thread.start is executed next time, if the configuration has been updated, capture the SpanContext and attach it to the task, and restore the SpanContext in the run method.
[0470] 6. Data collection: Report tracking data through Jaeger.
[0471] By selecting the embodiment of the application, through dynamic detection and LLM Agent analysis, context association is only performed when the parent thread is waiting for the child thread task, avoiding indiscriminate tracking transmission and reducing unnecessary performance overhead, which is particularly suitable for high-concurrency multi-thread scenarios.
[0472] Among them, through early bytecode injection, asynchronous LLM Agent analysis and dynamic configuration update, the application embodiment realizes cross-thread tracking context transmission in ThreadPoolExecutor and new Thread scenarios in combination with the OpenTracing specification. By obtaining the class file through Instrumentation, the backend decompiles to generate source code, and cooperates with the LLM Agent to analyze whether the parent thread is waiting for the child thread task, handles complex synchronization scenarios, significantly reduces performance overhead, and the scheme has high automation degree and is suitable for complex distributed system monitoring scenarios.
[0473] Based on the method provided in the first aspect, in the second aspect, the application provides a cross-thread monitoring device for application performance, wherein, as shown in Figure 3 the device 30 comprises:
[0474] The detection module 301 is configured to execute a target application performance monitoring task, and dynamically detect whether there is a cross-thread operation in the execution process of the target application performance monitoring task.
[0475] The thread analysis module 302 is configured to, if the cross-thread operation exists, acquire a parent-child relationship between threads, and determine whether a target parent thread needs to wait for a child thread;
[0476] The configuration update module 303 is configured to, if the target parent thread exists, create a configuration update thread, and modify a transmission configuration parameter between the target parent thread and the child thread through the configuration update thread, so that the target parent thread determines whether to transmit a trace context to the child thread based on the transmission configuration parameter.
[0477] Names of messages or information exchanged between the plurality of apparatuses in the embodiments of the present application are merely used for illustrative purposes, and are not intended to limit the scope of the messages or information.
[0478] In a third aspect, an example embodiment of the present application further provides an electronic device, comprising: at least one processor; and a memory connected with the at least one processor in communication. The memory stores a computer program capable of being executed by the at least one processor, and the computer program, when executed by the at least one processor, is configured to cause the electronic device to perform the method according to the embodiments of the present application.
[0479] An example embodiment of the present application further provides a non-transitory computer-readable storage medium storing a computer program, wherein the computer program, when executed by a processor of a computer, is configured to cause the computer to perform the method according to the embodiments of the present application.
[0480] An example embodiment of the present application further provides a computer program product comprising a computer program, wherein the computer program, when executed by a processor of a computer, is configured to cause the computer to perform the method according to the embodiments of the present application.
[0481] Reference Figure 4 A block diagram of an electronic device 400, which can be used as the server or the client of the present application, will now be described, which is an example of a hardware device that can be applied to various aspects of the present application. The electronic device is intended to represent a wide variety of digital electronic computing devices, such as laptops, desktops, workstations, personal digital assistants, servers, blade servers, mainframes, and other appropriate computing devices. The electronic device can also represent a wide variety of mobile devices, such as personal digital assistants, cellular telephones, smart phones, wearable devices, and other similar computing devices. The components shown here, their connections and relationships, and their functions, are meant to be examples only, and are not intended to limit the implementations of the present application described and / or claimed in this document.
[0482] As Figure 4 As shown, the electronic device 400 includes a computing unit 401 that can perform various appropriate actions and processes in accordance with a computer program stored in a read-only memory (ROM 402) or a computer program loaded into a random access memory (RAM 403) from the storage unit 408. In the RAM 403, various programs and data required for the operation of the electronic device 400 can also be stored. The computing unit 401, the ROM 402, and the RAM 403 are connected to each other through a bus 404. An input / output interface (I / O interface 405) is also connected to the bus 404.
[0483] A plurality of components in the electronic device 400 are connected to the I / O interface 405, including an input unit 406, an output unit 407, a storage unit 408, and a communication unit 409. The input unit 406 can be any type of device that can input information to the electronic device 400, and can receive inputted numerical or character information, as well as generate key signal inputs related to user settings and / or function controls of the electronic device. The output unit 407 can be any type of device that can present information, and can include, but is not limited to, a display, a speaker, a video / audio output terminal, a vibrator, and / or a printer. The storage unit 408 can include, but is not limited to, a magnetic disk, an optical disk. The communication unit 409 allows the electronic device 400 to exchange information / data with other devices through a computer network such as the Internet and / or various telecommunication networks, and can include, but is not limited to, a modem, a network card, an infrared communication device, a wireless communication transceiver, and / or a chipset, such as a Bluetooth™ device, a WiFi device, a WiMax device, a cellular communication device, and / or the like.
[0484] The computing unit 401 can be various general and / or special purpose processing components having processing and computing capabilities. Some examples of the computing unit 401 include, but are not limited to, a central processing unit (CPU), a graphics processing unit (GPU), various special-purpose artificial intelligence (AI) computing chips, various computing units running machine learning model algorithms, a digital signal processor (DSP), and any appropriate processor, controller, microcontroller, etc. The computing unit 401 performs various methods and processes described above. For example, in some embodiments, the aforementioned cross-thread monitoring of application performance method can be implemented as a computer software program tangibly embodied in a machine-readable medium, such as the storage unit 408. In some embodiments, part or all of the computer program can be loaded and / or installed onto the electronic device 400 via the ROM 402 and / or the communication unit 409. In some embodiments, the computing unit 401 can be configured to perform the aforementioned cross-thread monitoring of application performance method by any other appropriate means, such as by means of firmware.
[0485] Program code for carrying out operations of the methods of the present application can be written in any combination of one or more programming languages. This program code can be provided to a processor or controller of a general purpose computer, special purpose computer, or other programmable data processing apparatus to produce a machine, such that the program code, when executed by the processor or controller, produces the functions / operations specified in the flowcharts and / or block diagrams. The program code can be executed entirely on a machine, partially on a machine, partially on a machine as part of a standalone software package, or entirely on a remote machine or server.
[0486] In the context of the present application, a machine-readable medium can be a tangible medium that can contain or store program for use by or in connection with an instruction execution system, apparatus, or device. The machine-readable medium can be a machine-readable signal medium or a machine-readable storage medium. Machine-readable storage media can include, without limitation, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination of the foregoing. More specific examples of machine-readable storage media can include an electrical connection based on one or more wires, a portable computer disk, a hard disk, a random access memory (RAM), a read-only memory (ROM), an erasable programmable read-only memory (EPROM or Flash memory), an optical fiber, a portable compact disc read-only memory (CD-ROM), an optical storage device, a magnetic storage device, or any suitable combination of the foregoing.
[0487] As used in the present application, the terms "machine-readable medium" and "computer-readable medium" refer to any computer program product, apparatus and / or device (e.g., magnetic discs, optical disks, memory, Programmable Logic Devices (PLDs)) used to provide machine instructions and / or data to a programmable processor, including a machine-readable medium that receives machine instructions as a machine-readable signal. The term "machine-readable signal" refers to any signal that can be used to provide machine instructions and / or data to a programmable processor.
[0488] To provide for interaction with a user, the systems and techniques described here can be implemented on a computer having a display device (e.g., a CRT (cathode ray tube) or LCD (liquid crystal display) monitor) for displaying information to the user and a keyboard and a pointing device (e.g., a mouse or a trackball) by which the user can provide input to the computer. Other kinds of devices can be used to provide for interaction with a user as well; for example, feedback provided to the user can be any form of sensory feedback (e.g., visual feedback, auditory feedback, or tactile feedback); and input from the user can be received in any form, including acoustic, speech, or tactile input.
[0489] The systems and techniques described here can be implemented in a computing system that includes a back end component (e.g., as a data server), or that includes a middleware component (e.g., an application server), or that includes a front end component (e.g., a user computer having a graphical user interface or a Web browser through which a user can interact with an implementation of the systems and techniques described here), or any combination of such back end, middleware, or front end components. The components of the system can be interconnected by any form or medium of digital data communication (e.g., a communication network). Examples of communication networks include a local area network (LAN), a wide area network (WAN), and the Internet.
[0490] The computing system can include clients and servers. A client and server are generally remote from each other and typically interact through a communication network. The relationship of client and server arises by virtue of computer programs running on the respective computers and having a client-server relationship to each other.< / t> < / t> < / type> < / name> < / type> < / name> < / llmanalysisresult> < / loop1> < / condition1> < / type> < / name> < / type> < / param1> < / name> < / loop1> < / condition1> < / type> < / name> < / type> < / param1> < / name>
Claims
1. A method for cross-thread monitoring of application performance, the method comprising: The method comprises: in response to a JavaAgent start operation in a virtual machine, dynamically modifying the bytecode of a thread start method and / or a thread running method in a preset thread core class, adding dynamic detection execution logic in the thread start method and / or the thread running method execution logic, and performing a target application performance monitoring task; executing the thread start method or the thread running method, dynamically detecting the target application performance monitoring task, and determining whether there is a cross-thread operation in the target application performance monitoring task execution process; if the cross-thread operation exists, triggering an asynchronous analysis process, wherein the asynchronous analysis process comprises: asynchronously uploading a class file corresponding to the target application performance monitoring task to a backend server, and generating source code based on the class file using a decompilation tool; calling each middleware in a large language model intelligent component to analyze the source code, obtaining the parent-child relationship between threads, and determining whether there is a target parent thread that needs to wait for a child thread; if the target parent thread exists, creating a configuration update thread, and modifying the transmission configuration parameter between the target parent thread and the child thread through the configuration update thread, so that the target parent thread determines whether to transmit the tracking context to the child thread based on the transmission configuration parameter.
2. The method of claim 1, wherein, The dynamic detection execution logic comprises cross-thread operation detection logic, and the execution of the thread start method or the thread running method, the dynamic detection of the target application performance monitoring task, and the determination of whether there is a cross-thread operation in the target application performance monitoring task execution process comprise: when the target application performance monitoring task is submitted, executing the cross-thread operation detection logic to obtain a task instance of the target application performance monitoring task; determining whether the target application performance monitoring task has a cross-thread operation according to the task instance.
3. The method of claim 1, wherein, The method further comprises: if the target parent thread exists, associating the target parent thread with a target child thread that the target parent thread needs to wait for, and executing the configuration update thread.
4. The method of claim 1, wherein, The configuration update thread is configured as an asynchronous thread. The device is used to implement the method of any one of claims 1-5, and the device comprises:
5. The method of claim 1, wherein, a detection module configured to perform a target application performance monitoring task and dynamically detect whether there is a cross-thread operation in the target application performance monitoring task execution process; 6. An apparatus for cross-thread monitoring of application performance, the apparatus comprising: a thread analysis module configured to, if the cross-thread operation exists, obtain the parent-child relationship between threads and determine whether there is a target parent thread that needs to wait for a child thread; and The configuration updating module is configured to create a configuration updating thread if the target parent thread exists, and modify a transfer configuration parameter between the target parent thread and the child thread through the configuration updating thread, so that the target parent thread determines whether to transfer a trace context to the child thread based on the transfer configuration parameter.
7. An electronic device, comprising: The electronic device includes a processor and a memory storing a program; wherein the program includes instructions that, when executed by the processor, cause the processor to perform the method according to any one of claims 1-5.
8. A non-transitory computer-readable storage medium having stored thereon computer instructions, wherein, The computer instructions are used to cause a computer to perform the method according to any one of claims 1-5.
Citation Information
Patent Citations
Cross-thread calling chain context transmitting method and device and electronic device
CN109445880A
Cross-thread vulnerability analysis method and device based on code vaccine, equipment and medium
CN117272331A