Building Blocks
- Future
-
cancel()
: subsequent calls toisDone()
will always return true. - get
- get with timeout
- CompletableFuture
- Guide To CompletableFuture
- 3 Ways to Handle Exception In Completable Future
- handle()
- whenComplete()
- exceptionally()
Item | handle() | whenComplete() | exceptionally() |
---|---|---|---|
Access to success? | Yes | Yes | No |
Access to failure? | Yes | Yes | Yes |
Can recover from failure? | Yes | No | Yes |
Can transform result from T to U ? |
Yes | No | No |
Trigger when success? | Yes | Yes | No |
Trigger when failure? | Yes | Yes | Yes |
Has an async version? | Yes | Yes | Yes (Java 12) |
- Building blocks
- CountDownLatch:
- CyclicBarrier
- Phaser: sort of a dynamic version of CyclicBarrier
- Semaphore
- Lock
- API
- lock
- lockInterruptibly
- tryLock
- unlock
- Implementation
- ReentrantLock
- ReentrantReadWriteLock
- StampedLock
- Condition
Difference between Lock and Synchronized keyword
- fairness
- interruption
- A thread which is in “waiting” state to acquire the access to synchronized block, can't be interrupted.
Difference between CountDownLatch and CyclicBarrier

Fig 1: CountDownLatch and CyclicBarrier
Semaphore Analogy

Fig 2: Semaphore
- ThreadFactory
- BlockingQueue
- Producer-consumer pattern
- DelayQueue
- Lock and
synchronized
keyword - Synchronized keyword
- instance method
- code block
- static method
- The lock behind synchronized keyword is a reentrant lock.
Java Memeory Model and Volatile keyword
Related Readings
- JSR 133 (Java Memeory Model) FAQ
- Safe Construction Techniques
- Initialization of Classes and Interface
Java Memory Model
In short, there are two types of issues in a multithreaded program:
- Data race condition issue
- Visibility issue
and Java Meomery Model is used to define the behavior in a multithreaded environment.
Note:
- Reordering
- Cache
- JIT
- Compiler
- as-if-serial semantics
- Incorrectly Synchronized:
- There is a write of a variable by one thread
- There is a read of the same variable by another thread
- The write and read are not ordered by synchronization
- Synchronization
- mutual exclusion
- flush the cache to main memory
- invalidate the local processor cache and reload from main memory.
- Two types of orders
- Program's order
- Synchronization order
- happen-before
- Initialization guarantees for static fields
- If a field is set in a static initializer, it is guaranteed to be made visible, correctly, to any thread that access that classes.
- Detailed Initialization Procedure
- Initialization-on-demand holder idiom
- Singleton pattern
- The Initialization-on-demand holder idiom depends on the initialization guarantees for static fields.
1234567
private static class LazySomethingHolder {
public static Something something = new Something();
}
public static Something getInstance() {
return LazySomethingHolder.something;
}
- Java Initialization Safety Technique
- Object properly constructed: the references to it do not escape during construction.
- Keep the constructor simple: constructor should only be used to construct an object. Publishing the reference or register the object to other handlers are not the responsibility of constructor.
Volatile Keyword
- volatile = visible to other thread + disallow reordering
- visibility issue and visibility issue
- Any write to a volatile field happens before every subsequent read of the same field.
- happen-before relationship
- Reads and writes of volatile variables are assumed to occur in isolated blocks.
Thread
Life cycle of a thread
- State
- new
- runnable
- ready to run
- running
- non-runnable
- waiting
- wait
- join
- park
- timed waiting
- sleep
- join
- wait
- parkNano
- parkUntil
- blocked: waiting for a monitor lock and is trying to access a section of code that is locked by some other thread.
Notice that wait
can only be called from a synchronized block.
There are two types of threads:
- User thread
- Daemon thread
- Daemon thread does not block JVM exit.
- Daemon thread is generally used to support background tasks.
Note: Any thread inherits the daemon status of the thread that created it. The method setDaemon()
can only be called after the thread object has been created and the thread hasn't been started.
ThreadPoolExecutor and ExecutorService
Parameters
- corePoolSize
- maximumPoolSize
- keepAliveTime
ExecutorService
- ExecutorService
- termination
- shutdown
- shutdownNow
- awaitTermination
- ScheduledExecutorService
- schedule
- scheduleAtFixedRate
- scheduleWithFixedDelay
Note:
- ExecutorService needs to be shutdown because otherwise it may block the exist of JVM.
- ExecutorCompletionService uses a queue to store the results.
----- END -----
©2019 - 2023 all rights reserved