Java — Synchronization | Code Factory
2 min readMay 30, 2020
--
Index Page : Link
Donate : Link
WordPress Blog : Link
- Synchronization is a Modifier, applicable only for methods and block but not for classes and variablres.
- If multiple threads are trying to operate simultaneously on the same Java object then there may be a chance of data inconsistancy problem.
- To overcome this problem we should go for Synchronization keyword.
- If a method or block declared as Synchronized then at a time only 1 thread is allowed to execute that method or block on the given object, So that data inconsistancy problem will be resolved.
- The main advantage of Synchronized keyword is we can resolve data inconsistancy prolem but the main disadvantage of synchronized keyword is it increase waiting time of threads and creates performance problems. Hence if there is no specific requirement then it is not recommended to use Synchronized keyword.
- Internally Synchronization concept is implemented by using lock. Every object in Java has a unique lock. whenever we are using Synchronized keyword then only lock concept will come into the picture.
- If a thread wants to execute Synchronized method on the given object first it has to get lock of that object. Once thread got the lock then it is allow to execute any Synchronized method on that object.
- Once method execution completes automatically thread release a lock.
- Aquiring and releasing lock internally takes care by JVM and programmer not responsible for this activity.
- While a thread executing Synchronized method on the given object the remaining threads are not allowed to execute any Synchronized method simultaneously on the same object but remaining threads are allow to execute nonsynchronized methods simultaneously.
- Lock concept is implemented based on object but not based on method.
public class X {
synchronized area {
wherever we are performing
update opertation (add/remove/delete/replace)
ie. where state of object changing
}
non-synchronized area {
wherever object state wouldn't
be changed like read operation
}
}