Java Tutorials - Herong's Tutorial Examples - Version 7.03, by Dr. Herong Yang
Why Synchronization Is Needed in Multi-Threading Applications?
This section describes why synchronization is needed in multi-threading applications.
The biggest problem of allowing multiple threads sharing the same data set is that one operation in one thread could collide with another operation in another threads on the same data. When this happens, the result is un-desirable.
Let's use a bank application program as an example. Assuming that the program has multiple threads running, with each thread connecting one ATM system, and you have a saving account in the bank with $100.00, now you and your friend are going to two different ATMs at about the same time, and trying to withdraw $50.00 from your account, what do you think it will happen?
If the threads are running independently, the following could happen:
Time 01:01 02:01 03:01 04:01 +----------+---------+---------+------- Thread 1 Get Set Action You Account Account You Withdraw Balance Balance Receive $50.00 $100.00 $50.00 $50.00
Time 01:02 02:02 03:02 04:02 -+----------+---------+---------+------ Thread 2 Get Set Action Friend Account Account Friend Withdraw Balance Balance Receive $50.00 $100.00 $50.00 $50.00
Time 01:01 02:01 03:01 04:01 -----------++--------++--------++------ Account $100.00 $100.00 $50.00 $50.00
Both you and your friend will receive $50.00 each, and your account will still have $50.00. The bank could lose $50.00.
The solution to this problem is synchronization.
Last update: 2014.
Table of Contents
Execution Process, Entry Point, Input and Output
Primitive Data Types and Literals
Bits, Bytes, Bitwise and Shift Operations
Managing Bit Strings in Byte Arrays
Reference Data Types and Variables
StringBuffer - The String Buffer Class
System Properties and Runtime Object Methods
Generic Classes and Parameterized Types
Generic Methods and Type Inference
Lambda Expressions and Method References
Execution Threads and Multi-Threading Java Programs
ThreadGroup Class and "system" ThreadGroup Tree
►Synchronization Technique and Synchronized Code Blocks
►Why Synchronization Is Needed in Multi-Threading Applications?
Synchronization Technique - Lock and Synchronized Code
"synchronized" - How Java Supports Synchronization
BankingThread.java - Synchronization Sample Program
BankingThread.java - Synchronization Sample Program Output
Deadlock Condition Example Programs