Multitasking
Concurrency
Concurrency is when multiple computations are in progress at a time. Although only one computation is being executed at an instant.
Parallelism
Parallelism is when multiple computations are executed at a time. Therefore at any instant, multiple executions are ongoing simultaneously.
Parallel computing doesn't need multiple tasks. Even one task can be split up into multiple sub-tasks and be assigned to different cores of the processor.
The Art of Concurrency defines the difference as follows:
A system is said to be concurrent if it can support two or more actions in progress at the same time. A system is said to be parallel if it can support two or more actions executing simultaneously.
Multithreading
- Thread-based multitasking - Process of executing multiple Threads simultaneously.
- Only one thread can run at an instant in a process i.e. multithreading is execution.concurrency.
Advantages
- Doesn't block the user
- Saves time by performing many operations together
- Threads are independent. Failure of one doesn't affect another.
Thread Safety
- Stateless Implementation
- Source of error in most cases (multithreaded apps)
- Incorrectly sharing state between several threads
- Don't make your methods rely on external state, nor maintain any state at all
- Immutable Implementation
- Need to share states between threads → make them immutable
- Immutable Class = Thread safe
- #Synchronisation
Synchronisation
Its mechanism of coordinating events to occur at the same time.
It usually involves mechanisms like locks etc, which slows down the execution a little.
Deadlock
Deadlock can occur in execution.concurrency executions when two tasks are waiting for locks acquired by each other.