Concurrency, Parallelism, Processes, and Threads
Whether it’s Java or JavaScript, we encounter concurrency and parallelism issues in programming, which inevitably involve threads and processes. Let me organize these concepts here.
An Analogy for Concurrency and Parallelism
I saw a vivid analogy on Zhihu:
- You’re eating dinner and the phone rings, but you wait until you finish eating before answering. This means you don’t support concurrency or parallelism.
- You’re eating dinner and the phone rings, so you stop eating, answer the phone, and then continue eating afterward. This means you support concurrency.
- You’re eating dinner and the phone rings, so you eat while talking on the phone. This means you support parallelism.
OK, you can see that the fundamental difference between concurrency and parallelism is simultaneity
.
Threads and Processes
- A process is like a workshop in a factory. It represents a single task that the CPU can handle. At any given moment, the CPU is always running one process, while other processes are in a non-running state.
- In a workshop, there can be many workers who collaborate to complete a task. A thread is like a worker in the workshop. A process can include multiple threads.
- A CPU can only execute one process at a time, but a multi-core CPU can naturally execute multiple processes simultaneously.
Concurrency and Parallelism in JavaScript
Does concurrency exist in JavaScript?
YES, JavaScript has a concurrency model based on an event loop. The event loop is responsible for executing code, collecting and processing events, and executing sub-tasks in the queue.
Does parallelism exist in JavaScript? NO, JavaScript is single-threaded and can only do one thing at a time. However, note that browsers are multi-process and support concurrent connections, so multiple connections can be active simultaneously at any given moment. For example, after initiating concurrent XHR requests, multiple connections might be processing simultaneously, or when loading JS resources - these situations represent parallelism.
Concurrency and Parallelism in Java
As mentioned above, the key to parallelism lies in simultaneity. For example, we know machines have multi-core CPUs, but when the JVM starts, it occupies one process, and threads share process resources. So would the multi-core CPU be wasted?
NO
In Windows and Linux, the mapping relationship between Java threads and operating system threads is one-to-one. Therefore, threads can utilize multi-core CPUs.
Final Thoughts
I feel that simple problems seem to be pulled in different directions by various voices online. We still need to calm down, read some books, and think things through. Then everything becomes clear.