1. What is Synchronization in Thread
1. Synchronized is the modifier applicable only for methods and blocks but not for classes and variables.
2. If multiple threads trying to operate simultaneously on same java object then there may be a chance of data inconsistency problem.
3. To overcome this problem we should go for synchronized keyword.
4. If a method or block declared as synchronized then at a time only one thread is allowed execute that method or block on given object, so that data inconsistency problem will be resolved.
5. The main advantage of synchronized keyword is we can resolve data inconsistency problems but the main disadvantage of synchronized keyword is it increases waiting time of threads and creates performance problems.
6. Hence if there is no specific requirement then it is not recommended to use synchronized keyword.
7. Synchronized can’t use on constructors, instance blocks, static blocks, classes, variables.
2. Why Synchronization is needed
- When multiple threads access the same resource, sometimes memory inconsistency error will occur.
- If two threads t1, t2 are accessing same variable called ‘count’ of a same object.
- Initial value of count is ‘0’.
Int count = 0; - Now thread t1 incremented the value to 1.
count++; - At the same time thread t2 prints the value of ‘count’ as ‘0’ or ‘1’ no guarantee.
System.out.println(count); - Now data inconsistency will occurs.
- If above two statements will execute by same thread, it would be safe to print the value ‘1’ .
- But if two statements are executed in separate threads there is no guarantee.
No comments:
Post a Comment