Multithreading, Parallel and Async
Multithreading
A form of concurrency that uses multiple threads of execution.
Thread
, BackgroundWorker
, low-level, best to start with high-level abstractions like thread pool.
Parallel
Divide work among multiple threads that run concurrently.
Maximize the use of multiple processors of CPU. In most cases, work against built-in parallelism on server-side.
Async
Use futures or callbacks to avoid unnecessary threads.
Async with callback
1 | function doTaskAsync(msg, cb) { |
Drawbacks:
- Not sequential
- Inversion of control
Callback executed too early/late, too few/many times, swallow errors, …
Async with Promise
1 | function doTaskAsync(msg) { |
Async in ES7 (C# 5.0)
1 | async function doTasks() { |
Async in Scala
(see Promise and Future)
Async in Java
Java 5
interface java.util.concurrent.Future<T>::get()
is a blocking method.
Java 8
interface java.util.concurrent.CompletionStage<T>
is Promise
class java.util.concurrent.CompletableFuture<T> implements Future<T>, CompletionStage<T>
That’s all.
Async and Reactive
1 | Rx.Observable.fromEvent(..., "event a") |