What is synchronized modifier in Java?

What is synchronized modifier in Java?

What is synchronized modifier in Java?

What is synchronized modifier in Java?
  • Synchronized is the modifier applicable for methods and blocks but not classes and variables.
  • If multiple threads trying to operate simultaneously on the same java object then there may be a chance of data inconsistency problem this is called race condition.
  • We can overcome this problem by using synchronized keyword.
  • If a method or block declare as synchronized then at a time only one thread allows to execute that method or block on the given object so that data inconsistency problem will be resolved.
  • If several threads try to execute a synchronized method simultaneously, only one will be able to do it. The others will be paused until the first one exits the method. (In some sense it works much like a traffic light, making sure concurrent executions don’t collide.)
  • This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
  • But the main disadvantage of the synchronized keyword is it increases waiting time of thread and creates performs problems. Hence if there is no specific requirement then it is not recommended to use synchronized keyword.
  • Synchronized method should compulsorily contain implementation whereas abstract method doesn’t contain any implementation hence abstract synchronized is an illegal combination of modifiers for methods.

Leave a Reply

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

*