Java Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 6.00

Synchronization Technique - Lock and Synchronized Code

This section describes what is synchronization - a programming technique used in multi-threading applications with a synchronization lock to control execution of synchronized code.

Synchronization is a programming technique that involves 3 elements:

  • Lock: An object with two states: locked and unlocked.
  • Synchronized Block: A block of statements that is associated with a lock.
  • Synchronization Rule: When a synchronized block is encountered in a thread of execution, the associated lock will be checked. If the lock locked, the execution will be stopped until the lock is unlocked. If the lock is unlocked, the lock will be locked, and the synchronized block of statements will be executed. When the execution reaches the end of the synchronized block, the lock will be unlocked. With this rule, two synchronized blocks associated with same lock will never be executed at the same time.

Now let's see if we can use the synchronization technique in the bank application program to help the bank. Let's define a synchronization block starting from the "Get Account Balance" action to the "Set Account Balance" action in each thread, and associate the block with a lock. With this change, both you and your friend can still withdraw $50.00, but your account will have nothing left:

Time     01:01      02:01     03:01      04:02
         -----------+---------++--------++------- 
Lock     Unlocked   Locked    Locked     Unlocked
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     05:02
         -+----------+---------+---------+---------+------
Thread 2             Get       Get       Set
Action    Friend     Account   Account   Account   Friend
          Withdraw   Balance   Balance   Balance   Receive
          $50.00     Stopped   $50.00    $0.00     $50.00
Time     01:01      02:01     03:01      04:02     05:02
         -----------++--------++--------++---------+------
Account  $100.00    $100.00   $50.00     $0.00     $0.00

The synchronization technique did help the bank from losing money. But it also increased the total transaction time.

Sections in This Chapter

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

Dr. Herong Yang, updated in 2008
Synchronization Technique - Lock and Synchronized Code