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

推荐订阅源

F
Fortinet All Blogs
宝玉的分享
宝玉的分享
酷 壳 – CoolShell
酷 壳 – CoolShell
T
The Exploit Database - CXSecurity.com
Help Net Security
Help Net Security
腾讯CDC
Project Zero
Project Zero
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tailwind CSS Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 最新话题
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
N
News | PayPal Newsroom
C
Cybersecurity and Infrastructure Security Agency CISA
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
SegmentFault 最新的问题
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Proofpoint News Feed
A
Arctic Wolf
B
Blog RSS Feed
Forbes - Security
Forbes - Security
P
Privacy & Cybersecurity Law Blog
Attack and Defense Labs
Attack and Defense Labs
V2EX - 技术
V2EX - 技术
P
Proofpoint News Feed
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
T
Tenable Blog
MyScale Blog
MyScale Blog
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
W
WeLiveSecurity
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
罗磊的独立博客
The Last Watchdog
The Last Watchdog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Vulnerabilities – Threatpost
美团技术团队
Microsoft Security Blog
Microsoft Security Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Java Concurrency: From Threads to Thread Safety — Part 1
Aswathy Nair · 2026-05-18 · via DEV Community

I have been spending some time to dig deeper into Java concurrency - threads, synchronization, race conditions.
Most tutorials usually show you how to start a Thread, print "Hello World" which is not how any of this works in production.

This post covers my experiments, traps that I fell into, and what finally clicked - the non-"Hello World" way.

Processes vs. Threads

You can think of a Process as a factory. It has its own walls and its own resources. When you boot up a Java application, the JVM itself is the process.

A Thread is a worker inside your factory. The JVM automatically creates the main thread when your app starts. Every other thread you spawn is born from that main thread. Because all threads share the exact same workspace (the Java Heap memory), they can communicate instantly.

This shared memory is the root cause that makes multithreading dangerous. If one thread reads a value while another thread is halfway through updating it, the data gets corrupted. They don't even need to run at the exact same instant — one thread just needs to get in between another's read and write.

What threads share vs What they own

Shared between all threads in a process:

  • Heap memory — all your new SomeObject() calls
  • Static variables — one copy, every thread sees it
  • Class bytecode — the compiled .class files

Private to each thread:

  • Its own stack — local variables, method parameters, return addresses
  • Program counter — which line is this thread currently executing

Creating a thread: The Two Ways

If you want to hire a background worker in Java, there are two ways to do it.

Way 1: Extend the Thread Class

class MyWorker extends Thread {
    @Override
    public void run() {
        System.out.println("Running on: " + Thread.currentThread().getName());
    }
}
new MyWorker().start();

Enter fullscreen mode Exit fullscreen mode

Way 2: Implement Runnable

Runnable is an interface with a single run() method.

Runnable task = () -> {
    System.out.println("Running on: " + Thread.currentThread().getName());
};
new Thread(task).start();

Enter fullscreen mode Exit fullscreen mode

Note: Implementing Runnable keeps your class free to extend something else. In real codebases, always prefer Runnable.

Pitfall #1

Observe the below code:

new Thread(task).run();    // Looks right. Completely wrong.
new Thread(task).start();  // What you actually want.

Enter fullscreen mode Exit fullscreen mode

I ran this to see what happens:

Runnable task = () -> {
    System.out.println("Running on: " + Thread.currentThread().getName());
};

System.out.println("--- calling run() ---");
new Thread(task).run();

System.out.println("--- calling start() ---");
new Thread(task).start();

Enter fullscreen mode Exit fullscreen mode

Output:

    --- calling run() ---
    Running on: main
    --- calling start() ---
    Running on: Thread-1

Enter fullscreen mode Exit fullscreen mode

run() is just a regular method call. No new thread is born. The main thread itself jumps into run() and executes it. You never left main. Nothing concurrent happened.

start() actually tells the JVM — spin up a new thread, give it a stack, and let it run. That's when you see Thread-1 in the output.

Calling run() instead of start() is the worst kind of bug because it throws no errors, the code executes, but your application stays single-threaded.

The Static Variable and join()

Runnable has a fundamental flaw - run() method returns void. It behaves like fire and forget.

The hack was to use a shared static variable, whenever a value needs to be returned.

static int result = 0;

public static void main(String[] args) {
    Runnable task = () -> { result = 10 + 10; };
    new Thread(task).start();

    System.out.println(result); // What does this print?
}

Enter fullscreen mode Exit fullscreen mode

If you run this, it will almost always print 0.
Because the main thread is fast. It starts the background worker, and then immediately races to the next line and prints result before the background worker even computes.

To fix this, we have to force the main thread to wait using .join().

    Thread t1 = new Thread(task);
    t1.start();
    t1.join(); // Tells the main thread: Stop here until t1 is completely dead.
    System.out.println(result); // Now prints 20

Enter fullscreen mode Exit fullscreen mode

Pitfall #2: The Race Condition

The static variable combined with .join() works for one thread, but it falls apart in production code.
If you have two threads writing to that shared result variable at the same time, their data overwrites each other unpredictably. The output will change from run to run making it difficult to debug.

Callable & FutureTask

Static variable hack is so unpredictable, Java introduced Callable.

It is exactly like Runnable, but it returns a value and can throw exceptions.

But there is a catch: Thread doesn't accept Callable directly. The compiler will throw an error if you try new Thread(myCallable).

So Java has FutureTask — a wrapper that accepts a Callable and is itself Runnable, so Thread can take it:

    Callable<String> task = () -> {
        return "Result from: " + Thread.currentThread().getName();
    };

    FutureTask<String> futureTask = new FutureTask<>(task);
    new Thread(futureTask).start();

    System.out.println(futureTask.get()); // blocks until result is ready

Enter fullscreen mode Exit fullscreen mode

ExecutorService & Future

Above code works fine. But we are creating a new Thread for every task. In real production case, this can easily spin up thousands of threads and result in OutOfMemoryError.

To put a check on this, a manager for thread creation is needed: an ExecutorService.

When you submit a Callable to a thread pool, the manager gives you back a Future.

A Future is basically a promise — the worker is on it, and the result will show up here when it's done. Main thread doesn't freeze, it just calls future.get() when it actually needs the value.

// 1. Initialize the Manager (A pool of 10 workers)
ExecutorService executorService = Executors.newFixedThreadPool(10);

// 2. Submit the task
Future<String> future = executorService.submit(myCallable);

// 3. Check the result
System.out.println(future.get());

executorService.shutdown();

Enter fullscreen mode Exit fullscreen mode

Pitfall #3

The .get() method is blocking. When your main thread hits future.get(), it pauses and waits for the background worker to populate the box.

If that background worker gets stuck in an infinite loop, the main thread waits forever. Your application freezes. In production, never call .get() without a timeout.

try {
    System.out.println(future.get(3, TimeUnit.SECONDS));
} catch (TimeoutException e) {

    System.out.println("Task took too long!");
    future.cancel(true); // <--- Kill the zombie worker
}

Enter fullscreen mode Exit fullscreen mode

Note: cancel(true). If you give up waiting, tell the worker to stop. Otherwise, it stays alive in the background keeping CPU running forever as a "zombie worker".

Shared State

Even with thread pools and futures, what happens when all threads try to access the exact same data?

Imagine a simple Bank Account:

public class BankAccount {
    private int balance = 0;

    public void deposit() {
        balance ++; 
    }

    public int getBalance() {
        return balance;
    }
}

Enter fullscreen mode Exit fullscreen mode

Let's use our ExecutorService to submit exactly 10000 tasks. Every single task will simply call deposit() on the exact same bank account.

ExecutorService service = Executors.newFixedThreadPool(10);
BankAccount bankAccount = new BankAccount();

// Submit 10,000 deposit tasks to the pool
for (int i = 0; i < 10000; i++) {
    service.submit(() -> bankAccount.deposit());
}

// wait for the workers to finish
service.shutdown(); 
service.awaitTermination(5, TimeUnit.SECONDS);

System.out.println("Final balance: " + bankAccount.getBalance());

Enter fullscreen mode Exit fullscreen mode

10000 deposits should equal a final balance of 10000. But if you run this code, you will get 9998. Or 9991. Or 9997.

Pitfall #4

For us, balance++ is one step. But to a CPU, it is three:

  1. Read the current balance.
  2. Add 1 to it.
  3. Write the new value back.

For example: If Thread A reads the balance at 5000, and Thread B reads it before A writes back, they both see 5000. Both add 1, both write 5001. Two deposits, one update lost.

Fixing the Race Condition

First thing to try is to use synchronized.

public synchronized void deposit() {
    balance ++;
}

Enter fullscreen mode Exit fullscreen mode

When you add synchronized to a method, Java automatically uses the object itself (in this case, your bankAccount instance) as a lock.

    * Thread 1 grabs the lock, runs the method.
    * Threads 2 through 10000 hit the locked door and OS put all those to sleep state (`BLOCKED`)
    * Thread 1 finishes, returns the lock, and wakes up Thread 2.
    * Repeat 10000 times.

Enter fullscreen mode Exit fullscreen mode

synchronized works fine until many threads are constantly fighting for the same lock. When contention is high, thousands of threads hitting the same method, the constant blocking and waking becomes the bottleneck and you can end up slower than a single thread. That's when you look for alternatives.

Lock-Free Concurrency (Atomics)

Instead of locks, we can use hardware-level instructions. Modern CPUs have a feature called Compare-And-Swap (CAS).
It says:
Update a value only if it has not been changed by another thread.

In Java, we use AtomicInteger which is built on CAS mechanism. Here is the code:

public class BankAccount {
    private AtomicInteger balance = new AtomicInteger(0);

    // No synchronized keyword needed!
    public void deposit() {
        balance.incrementAndGet();
    }

    public int getBalance() {
        return balance.get();
    }
}

Enter fullscreen mode Exit fullscreen mode

If you run 10000 threads against this, your balance prints 10000 every single time. No locks, no blocking. But it's not magic — see the note below

Note: CAS isn't free. Under the hood, if the update fails, the thread retries in a loop — it doesn't sleep, it spins. With few threads this is fast. With thousands of threads all spinning on the same value, you're burning CPU on retries. synchronized at least puts threads to sleep. Pick based on your contention level.


What's Next?

We will be discussing more on CompletableFuture, ConcurrentHashMap, CountDownLatch, DeadLocks and more in further posts.