Java.Multithreading.What is the difference between “concurrency” and “parallelism”?

🧠 Quick Definition:

TermDefinition
ConcurrencyDealing with lots of tasks at once (not necessarily simultaneously)
ParallelismActually doing lots of tasks at the same time

🔄 Concurrency: Switching Between Tasks

Think of it like a single chef cooking multiple dishes:

  • The chef is switching between boiling water, chopping veggies, and baking.
  • Only one thing happens at a time, but the chef manages multiple tasks efficiently.

📌 In code:

  • You might use threads, coroutines, or async/await.
  • You focus on structure, responsiveness, and handling many things.
// Threads taking turns (concurrently)
Thread A -> read DB
Thread B -> handle HTTP request
Thread C -> log user info

Parallelism: Doing Tasks Simultaneously

Now imagine multiple chefs, each cooking a different dish at the same time:

  • They can chop, boil, and fry in parallel, using different hands or kitchens!

📌 In code:

  • Requires multiple CPU cores
  • True simultaneous execution
// Tasks run truly in parallel
ForkJoinPool pool = new ForkJoinPool(4);
pool.submit(() -> {
    task1(); // runs on core 1
    task2(); // runs on core 2
});

💬 A Famous Quote (Rob Pike):

“Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.”

🧩 Summary Table

FeatureConcurrencyParallelism
FocusStructure, responsivenessSpeed, throughput
Can run on 1 CPU?✅ Yes❌ Needs multiple CPUs/cores
ExampleWeb server handling many requestsMatrix multiplication using 8 cores
Java ToolsThreads, Executors, FutureForkJoinPool, parallelStream()
AnalogyOne cook juggling dishesMultiple cooks cooking simultaneously
This entry was posted in Без рубрики. Bookmark the permalink.