-
Notifications
You must be signed in to change notification settings - Fork 0
Synchronization
The tool needed to prevent thread interference and memory consistency errors is synchronization. Synchronization in Java means allowing controlled access of a shared resource to avoid problem like deadlock. If your code is executing in a multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior. Synchronized allows only one thread of execution to access the resource at the same time.
Synchronization can be accrued by using
- Synchronized method (Instance method or static method)
- Synchronized block – sometimes we need to synchronize only a part of the method
Both these mechanism helps to access intrinsic lock on object. Synchronized keyword causes a performance cost. A synchronized method in Java is very slow and can degrade performance. So we must use synchronization keyword in java when it is necessary else, we should use Java synchronized block that is used for synchronizing critical section only.
- To prevent thread interference
- To prevent memory consistency problem
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
- Java Concepts
- Multithreading
- Java 8 Features