Synchronized in Thread


  • While running multi-threads, there will be a significant problem when those threads try to use same resource.
    • For example, multiple people try to deposit money into the same account. Let’s say initial balance is $0. If 5 people are accessing at the same time, they all will see $0 as an account balance. Then, after all people’s deposit of $500 each, it will have $500 for total deposit. This is because they accessed at the same time, and they all updated balance as $500. However, the balance should be $2,500.
  • So, lock is needed to avoid other thread trying to use the same resource at the same time.
  • That lock can be done by Synchronized.

There is two ways to use synchronized.

  • Synchronized method
public synchronized /* Method name  */(){
  • Synchronized block
synchronized( /* Object to be shared */ ){

Leave A Comment

Your email address will not be published. Required fields are marked *