Concurrency vs Parallel Execution in Java
In Java, both concurrency and parallelism are used to handle multiple
tasks, but they differ in their approach and execution:
1. Concurrency
Definition: Concurrency refers to the ability of a program to
manage multiple tasks at the same time. However, these tasks may
not necessarily execute simultaneously.
Key Idea: Tasks are interleaved, meaning the CPU switches
between tasks quickly, giving the illusion of simultaneous execution.
Example: A single-core CPU running multiple threads. The threads
take turns using the CPU, but only one thread is active at any given
moment.
Use Case: Useful when tasks involve waiting (e.g., I/O operations)
or when you want to improve responsiveness without requiring
multiple cores.
2. Parallelism
Definition: Parallelism involves executing multiple tasks
simultaneously, typically on multiple CPU cores.
Key Idea: Tasks are truly executed at the same time, leveraging
multi-core processors.
Example: A multi-core CPU running multiple threads, where each
thread is assigned to a separate core.
Use Case: Ideal for computationally intensive tasks that can be
divided into smaller, independent subtasks.
Reentranet Lock:
A reentrant lock (also known as a reentered lock) in Java is a type of
mutual exclusion (mutex) lock that allows the same thread to acquire
the lock multiple times without causing a deadlock.
In Java, this is implemented by the class ReentrantLock from the
package [Link].
Normally, if a thread already holds a lock and tries to acquire it again, it
would block (causing a deadlock).
But a ReentrantLock keeps track of how many times the current thread
has acquired it.
Each lock() call must be matched with a unlock() call.
A deadlock happens when two or more threads are waiting for each other
to release a lock, and none of them ever does — so the program freezes.