Java virtual threads affect observability and monitoring strategies need to be adjusted to adapt. 1. The thread ID is no longer unique, and traditional tools are difficult to locate problems; 2. The thread name in the log is invalid, and MDC and distributed tracking are required to connect the request link; 3. The existing APM tools are insufficiently supported, so JDK should be upgraded and new tools such as JFR should be used; 4. The framework and community are gradually adapted, and we need to continue to pay attention to progress.
Virtual Threads in Java are one of the key features introduced by Project Loom, which greatly improves Java's performance and scalability in high concurrency scenarios. But at the same time, the introduction of virtual threads has also brought new challenges to observability. Traditional monitoring methods based on operating system threads often seem powerless when facing thousands or even hundreds of thousands of virtual threads.

Let’s take a look at the specific impact of virtual threads on observability and how we should deal with it.
Virtual threads change the thread model
Virtual threads are essentially lightweight threads managed by the JVM. They do not map directly to the threads of the operating system like platform threads, but are reused on a small number of platform threads through a scheduler. This design makes it very easy to create hundreds of thousands of virtual threads, but it also means:

- Thread ID no longer uniquely identifies an execution unit
- Traditional thread name, thread status and other information have become insufficient
- The stack trace may contain a lot of information about virtual thread switching, making it difficult to quickly locate problems.
If you used to checking blocking or deadlocking through jstack
or APM tools before checking the thread stack, you may now find that these tools "can't see clearly" the relationship between virtual threads.
Logging requires clearer context
In a multithreaded environment, the thread name is usually recorded in the log to help track the request processing path. However, in virtual thread scenarios, the thread name changes frequently and the life cycle is short, which will make the thread information in the log lose its reference value.

For example: You see a bunch of VirtualThread[#234]/runnable
in the log, and you don't know which request or task it belongs to.
Solutions to this problem include:
- Use MDC (Mapped Diagnostic Context) to record unique identifiers at the request level, such as trace ID or request ID
- In conjunction with distributed tracking systems (such as Jaeger and OpenTelemetry), the execution paths of virtual threads are associated
- In asynchronous or structured concurrency, ensure context information is passed between tasks
In this way, even if the thread changes, you can connect the related operations and see the entire calling link clearly.
Monitoring and diagnostic tools require upgrade support
At present, many Java monitoring tools cannot recognize virtual threads well. For example, some APM tools may only count the number of platform threads, and ignore the actual operation of virtual threads.
To improve observability, you can:
- Upgrade to JDK 21 and use the latest version of diagnostic tools that support virtual threads (such as JFR)
- Leverage new APIs provided by the JVM (such as
Thread.ofVirtual()
) to clearly distinguish between virtual threads and platform threads - Pay attention to the progress of community and vendor observation support for virtual threads. For example, frameworks such as Spring, Micronaut, Quarkus have begun to adapt
JFR (Java Flight Recorder) is a good choice in this regard. It can already support event recording and analysis of virtual threads, and can be used to track virtual threads' scheduling, blocking, CPU usage, etc.
Let's summarize
Although Java's virtual threads improve concurrency capabilities, they also break our previous monitoring and debugging methods of threads. To maintain good observability, we need:
- Replace the log policy that depends on the thread name and use the request-level context instead.
- Upgrade your monitoring and tracking system to support virtual threading
- Use JFR and new JDK APIs to gain insight into virtual thread behavior
Basically that's it. After all, virtual threads bring not insurmountable obstacles, but a new normal that requires us to adjust our thinking to adapt.
The above is the detailed content of Java Virtual Threads and Observability. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

Lazy loading only queries when accessing associations can easily lead to N 1 problems, which is suitable for scenarios where the associated data is not determined whether it is needed; 2. Emergency loading uses with() to load associated data in advance to avoid N 1 queries, which is suitable for batch processing scenarios; 3. Emergency loading should be used to optimize performance, and N 1 problems can be detected through tools such as LaravelDebugbar, and the $with attribute of the model is carefully used to avoid unnecessary performance overhead.

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

LaravelOctaneisaperformance-boostingpackagethatimprovesresponsetimesandthroughputbyservingLaravelapplicationsviaSwoole,OpenSwoole,orRoadRunner.1.UnliketraditionalPHP-FPM,whichbootsLaraveloneveryrequest,Octaneloadstheapponceandkeepsitinmemory.2.Thisel
