惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
博客园 - 叶小钗
爱范儿
爱范儿
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
Apple Machine Learning Research
Apple Machine Learning Research
美团技术团队
T
Tailwind CSS Blog
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Your Virtual Threads Are Leaking: Why ScopedValue is the ...
Vishal Aggar · 2026-04-24 · via DEV Community

Vishal Aggarwal

Your Virtual Threads Are Leaking: Why ScopedValue is the Only Way Forward.

If you're spinning up millions of Virtual Threads but still clinging to ThreadLocal, you're building a memory bomb. Java 21 changed the game, and if you haven't migrated to ScopedValue yet, you're missing the actual point of lightweight concurrency.

Why Most Developers Get This Wrong

  • The Scalability Trap: Treating Virtual Threads like Platform Threads. Thinking millions of ThreadLocal maps won't wreck your heap is a rookie mistake; the per-thread overhead adds up fast when you scale to 100k+ concurrent tasks.
  • The Mutability Nightmare: Using ThreadLocal.set() creates unpredictable side effects in deep call stacks. In a world of massive concurrency, mutable global state is a debugging death sentence.
  • Manual Cleanup Failures: Relying on try-finally to .remove() locals. It inevitably fails during unhandled exceptions or complex async handoffs, leading to "ghost" data bleeding between requests.

The Right Way

Shift from long-lived, mutable thread-bound state to scoped, immutable context propagation.

  • Use ScopedValue.where(...) to define strict, readable boundaries for your data (like Tenant IDs or User principals).
  • Embrace Structured Concurrency: use StructuredTaskScope to ensure context propagates automatically and safely to child threads.
  • Treat context as strictly immutable; if you need to change a value, you re-bind it in a nested scope rather than mutating the current one.
  • Optimize for memory: ScopedValue is designed to be lightweight, often stored in a single internal array rather than a complex hash map.

Show Me The Code

private final static ScopedValue<String> TENANT_ID = ScopedValue.newInstance();

public void serveRequest(String tenant, Runnable logic) {
    // Context is bound to this scope and its children only
    ScopedValue.where(TENANT_ID, tenant).run(() -> {
        performBusinessLogic();
    });
    // Outside this block, TENANT_ID is automatically cleared
}

void performBusinessLogic() {
    // O(1) access, no risk of memory leaks, completely immutable
    String currentTenant = TENANT_ID.get(); 
    System.out.println("Working for: " + currentTenant);
}

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Memory Efficiency: ScopedValue eliminates the heavy ThreadLocalMap overhead, making it the only viable choice for high-density Virtual Thread architectures.
  • Safety by Default: Immutability isn't a limitation; it's a feature that prevents "spooky action at a distance" across your call stack.
  • Structured Inheritance: Unlike InheritableThreadLocal, which performs expensive data copying, ScopedValue shares data efficiently with child threads within a StructuredTaskScope.

Want to go deeper? javalld.com — machine coding interview problems with working Java code and full execution traces.