Hi Ninja,
In one simple sentence taken from java tutorials:
"
Synchronized Methods describes a simple idiom that can effectively prevent thread interference and memory consistency errors."
Imagine that you are buying a ticket for the cinema, the person who is selling you the ticket can do 3 actions (functions):
- Decrement the number of tickets remaining (when someone buy a ticket)
- Increment the number of tickets remaining (when someone cancel a ticket)
- Inform to the clients how many tickets remain.
Assuming that the person who is selling the tickets have to do the following to accomplish each task:
Decrement:
1.- Retrieve the number of tickets.
2.- Decrease in one.
3.- Store the value in the system.
Increment: Same as decrement but step 2 increasing instead of decreasing.
Now let's imagine that two clients are being served at the same time: Client A buy a ticket and Client B cancel a ticket.
This is what the seller does:
Retrieve the value for the client A (Answer: 4)
Retrieve the value for the client B (Answer: 4)
Decrease in 1 for the client A (now for the client A is 4-1=3)
Increase in 1 for the cancelation of client B (Now for the client B is (4+1=5)
Store the value for the client A (the seller stores 3)
Store the value for the client B (the seller stores 5)
Final result: Remaining tickets 5 instead of 4.
That is what is called Thread interference and synchronized methods makes the seller to serve only one client at the same time.
Try to read java sun tutorials for more information
HERE