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:

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.

Last update: 2014.

Table of Contents

 About This Book

 Installing JDK 1.8 on Windows

 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

 Garbage Collection and the gc() Method

 Outdated Tutorials

 References

 PDF Printing Version