In this article, we will talk of synchronized keyword in Java. It is critical for any programmer to understand the consequences of race condition which needs to be avoided. We will explain race condition first then explain how we can resolve it using the synchronized keyword.
In any programming language, race-condition occurs when one or more thread tries to access a resource. When this happens one can not guarantee the outcome of the results.
For a simple example if you want to withdraw dome money and at the same time, joint account holders try to withdraw money at the same time. Now banking software has to be intelligent to allow one transaction at the same time otherwise one can overdraw and pay penalty further. A better way of explaining is that if you £100s in the deposit account and you and your joint partner try to withdraw at the same time. Your transaction account will assume £100s and at the end of both transactions, your account will be negative £100. You may not have desired it.
In Java two synchronized idioms are provided:
1. Method based synchronization.
2. Synchronization statements.
This guarantees that if there are two synchronized methods for debit and credit method then only one thread will get the monitor and others will be blocked in the simple term. It automatically established happen-before relationship to any subsequent call to the method for the same object.
Synchronized methods enable only one thread to access the object or resource hence preventing thread interference and memory consistency. The basic rule is that if an object is visible for more than one thread then all reads and writes should be synchronized.
Example:
synchronized debit(…){
// resource or object can be used successfully.
}
synchronized credit(…){
// resource or object can be used successfully.
}
There is the number of issues with the synchronized keyword which we will discuss in the later chapters. Business Integration Software has a number of training modules regarding synchronization.
Assessment Management Software
Multiple Choice Question Software