Ch.01 – Single Threaded Execution

Published by

on


Synchronized

  • synchronized method ensures only one thread can execute the method at a time.
    • All of the methods which access shared resources(critical section) should have a synchronized keyword to guard the state of shared resource.
  • synchronized methods are slower
    1. It takes time to acquire a lock of the object
    2. 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.
  • synchronzied method can be implemented using lock() and unlock() inside of try-finally condition.
    • unlock() must be declared inside of finally() 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 synchronized affects the performance of the application. Abusing it may slower the application. Therefore, a single threaded application doesn’t need to use this keyword
  • 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

  1. Multiple shared resources(threads) exist.
  2. A thread which acquired lock of a shared resource tries to acquire another lock of another shared resource.
  3. 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 the finally() statement

Leave a comment