Class 2 |
Intermediate Java 30-IT-397 |
|
Synchronization
-
Many times, different threads need to access the same data or variable.
-
A race condition results if multiple threads corrupt a variable.
-
To ensure that this does not happen, you must synchronize the data
or methods that are called.
-
The Bank Account example in the book (pg 44-45) demonstrates this well.
-
To synchronize an entire method, we simply add the synchronize
keyword to that method's signature.
-
Example: public void transfer(int amount) { becomes
public synchronized void transfer(int amount) {
-
Why not just synchronize everything?
-
Synchronization is expensive. It requires more processing and slows
down the program, so we should only use it when we need it.
-
Methods that simply return constants definitely do not need to be synchronized.
Only methods that contain atomic transactions.

Created by: Brandan Jones
December 17, 2001