Java's virtual threads offer a lightweight alternative to traditional OS threads, enabling efficient concurrency management. But understanding their behavior is crucial for optimal performance. This blog post dives into pinning, a scenario that can impact virtual thread execution, and explores techniques to monitor and address it.
Virtual Threads: A Lightweight Concurrency Approach
Java's virtual threads are managed entities that run on top of the underlying operating system threads (carrier threads). They provide a more efficient way to handle concurrency compared to creating numerous OS threads, as they incur lower overhead. The JVM maps virtual threads to carrier threads dynamically, allowing for better resource utilization.
Managed by the JVM: Unlike OS threads that are directly managed by the operating system, virtual threads are created and scheduled by the Java Virtual Machine (JVM). This allows for finer-grained control and optimization within the JVM environment.
Reduced Overhead: Creating and managing virtual threads incurs significantly lower overhead compared to OS threads. This is because the JVM can manage a larger pool of virtual threads efficiently, utilizing a smaller number of underlying OS threads.
Compatibility with Existing Code: Virtual threads are designed to be seamlessly integrated with existing Java code. They can be used alongside traditional OS threads and work within the familiar constructs like Executor and ExecutorService for managing concurrent.
The figure below shows the relationship between virtual threads and platform threads:
Pinning: When a Virtual Thread Gets Stuck
Pinning occurs when a virtual thread becomes tied to its carrier thread. This essentially means the virtual thread cannot be preempted (switched to another carrier thread) while it's in a pinned state. Here are common scenarios that trigger pinning:
- Synchronized Blocks and Methods: Executing code within a synchronized block or method leads to pinning. This ensures exclusive access to shared resources, preventing data corruption issues.
Code Example:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) throws InterruptedException { final Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i <p>In this example, when a virtual thread enters the synchronized block, it becomes pinned to its carrier thread, but this is not always true. Java's synchronized keyword alone is not enough to cause thread pinning in virtual threads. For thread pinning to occur, there must be a blocking point within a synchronized block that causes a virtual thread to trigger park, and ultimately disallows unmounting from its carrier thread. Thread pinning could cause a decrease in performance as it would negate the benefits of using lightweight/virtual threads.</p> <p>Whenever a virtual thread encounters a blocking point, its state is transitioned to PARKING. This state transition is indicated by invoking the VirtualThread.park() method:<br> </p> <pre class="brush:php;toolbar:false">// JDK core code void park() { assert Thread.currentThread() == this; // complete immediately if parking permit available or interrupted if (getAndSetParkPermit(false) || interrupted) return; // park the thread setState(PARKING); try { if (!yieldContinuation()) { // park on the carrier thread when pinned parkOnCarrierThread(false, 0); } } finally { assert (Thread.currentThread() == this) && (state() == RUNNING); } }
Let's take a look at a code sample to illustrate this concept:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i
- Native Methods/Foreign Functions: Running native methods or foreign functions can also cause pinning. The JVM might not be able to efficiently manage the virtual thread's state during these operations.
Monitoring Pinning with -Djdk.tracePinnedThreads=full
The -Djdk.tracePinnedThreads=full flag is a JVM startup argument that provides detailed tracing information about virtual thread pinning. When enabled, it logs events like:
- Virtual thread ID involved in pinning
- Carrier thread ID to which the virtual thread is pinned
- Stack trace indicating the code section causing pinning
Use this flag judiciously during debugging sessions only, as it introduces performance overhead.
-
Compile the our demo code:
javac Main.java
-
Start the compiled code with the -Djdk.tracePinnedThreads=full flag:
java -Djdk.tracePinnedThreads=full Main
-
Observe the output in the console, which shows detailed information about virtual thread pinning:
Thread[#29,ForkJoinPool-1-worker-1,5,CarrierThreads] java.base/java.lang.VirtualThread$VThreadContinuation.onPinned(VirtualThread.java:183) java.base/jdk.internal.vm.Continuation.onPinned0(Continuation.java:393) java.base/java.lang.VirtualThread.parkNanos(VirtualThread.java:621) java.base/java.lang.VirtualThread.sleepNanos(VirtualThread.java:791) java.base/java.lang.Thread.sleep(Thread.java:507) Counter.increment(Main.java:38) <== monitors:1 Main.lambda$main\$0(Main.java:13) java.base/java.lang.VirtualThread.run(VirtualThread.java:309) Final counter value: 200
Fixing Pinning with Reentrant Locks
Pinning is an undesirable scenario which impedes the performance of virtual threads. Reentrant locks serve as an effective tool to counteract pinning. Here's how you can use Reentrant locks to mitigate pinning situations:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.ReentrantLock; public class Main { public static void main(String[] args) { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i <p>In the updated example, we use a ReentrantLock instead of a synchronized block. The thread can acquire the lock and release it immediately after it completes its operation, potentially reducing the duration of pinning compared to a synchronized block which might hold the lock for a longer period.</p><h2> 결론적으로 </h2> <p>Java의 가상 스레드는 언어의 진화와 기능에 대한 증거입니다. 이는 기존 OS 스레드에 대한 새롭고 가벼운 대안을 제공하여 효율적인 동시성 관리를 위한 다리를 제공합니다. 스레드 고정과 같은 핵심 개념을 깊이 파고들고 이해하는 데 시간을 투자하면 개발자는 이러한 경량 스레드의 잠재력을 최대한 활용할 수 있는 노하우를 얻을 수 있습니다. 이러한 지식은 개발자가 향후 기능을 활용할 수 있도록 준비할 뿐만 아니라 현재 프로젝트에서 복잡한 동시성 제어 문제를 보다 효과적으로 해결할 수 있도록 지원합니다.</p>
위 내용은 JVM의 가상 스레드 메커니즘에서 고정 탐색의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.
