
Synchronized
synchronizedmethod ensures only one thread can execute the method at a time.- All of the methods which access shared resources(critical section) should have a
synchronizedkeyword to guard the state of shared resource.
- All of the methods which access shared resources(critical section) should have a
- synchronized methods are slower
- It takes time to acquire a lock of the object
- Waits when there’s a collision between threads
- synchronized block acquires the lock of the instance.
- ex)
synchronized (this) {} - If the instance is different, the block can be executed at the same time.
- ex)
synchronziedmethod can be implemented usinglock()andunlock()inside oftry-finallycondition.unlock()must be declared inside offinally()statement to ensure it release lock even when error occurs.- This is called as Before/After pattern.
public synchronized void myMethod() {
}
// equals to
public void myMethod() {
lock();
try {
...
} finally {
unlock();
}
}
Usecases of Single Threaded Execution
- Multi-Thread
- Using
synchronizedaffects the performance of the application. Abusing it may slower the application. Therefore, a single threaded application doesn’t need to use this keyword
- Using
- Multi-Threads accessing the same resource
- If the multi threads do not interfere each other and totally isolated, you don’t need to use Single Threaded Execution
- Possible state change
- Single Threaded Execution is used for preventing the state change of the shared resources. If the state does not change, you don’t need to use.
DeadLock
Condition
- Multiple shared resources(threads) exist.
- A thread which acquired lock of a shared resource tries to acquire another lock of another shared resource.
- No order of lock acquiring
Removing any of the deadlock conditions can remove the deadlock.
Semaphore
- Unlike single-threaded-execution which allows only 1 thread to be accessing shared resources at a time, semaphore allows n threads to access the resources.



- Note that
semaphore.release()is being executed inside of thefinally()statement

Leave a comment