Java Synchronization Flashcards
Why we need Java synchronization ?
When there is two or more threads, they might use same resource ,for example, if multiple threads try to write within the same file , they may corrupt data , one of threads can override data or while one thread try to open a file at the same time another thread may close it, so it produce unforeseen results.
So , there is need to synchronize action of multiple threads and make sure only one thread can access the resource at a given point in time.This is implemented using a concept called monitors
What is monitor concept ?
Each object in java is associated with a monitor , which a thread can lock or unlock. Only one thread at a time can hold a lock on a monitor .
synchronized
used to synchronize java thread tasks.
synchronized Syntax
synchronized(objectRef){
}
=> objectRef is a reference to an object associated with a monitor (which only one thread can hold a lock at a time)
Example of synchronized use
We write two threads for a counter program
=> Without synchronized() the count is not in sequence but when we write print counter method inside synchronized(PrintCounterRef){
PrintCounterMethod()} the count is in sequence.
Static Synchronization
when we use this type of synchronization , the thread on synchronization region have access and all other threads are blocked until the thread allowed ends
Syntax of Static Synchronization
static synchronized returnType nameOfMethod( Type parameters) {
// code
}
inter-thread communication
happens when threads exchange information
How to achieve inter-thread communication ?
we use this methods:
*wait(): a thread wait until another thread invoke notify().
*notify():Wakes up a single thread waiting on this object’s monitor
*notifyAll(): Wakes up all threads that called wait() on the same object.
Reentrant Monitor(ReentrantLock)
is mechanism for synchronization that allows same thread acquire same lock multiple times without causing deadLock.
=> It is one of deadLock solutions
How Reentrant Monitor works ?
*Reentrancy: a monitor is re-entrant when its thread can re-enter same synchronized block or method it already holds lock on
*Hold count : when a thread acquire a reentrant lock it increments hold count , same thing happens when it acquires the same lock again and opposite happen when it release the lock.Hold count is set to 0 when a lock is fully released
Reentrant Monitor Benefits
*Avoids DeadLock
*More flexible than synchronized