A synchronisation can be difficult for a new starter and may cause production issues and performance problems as well. We will try to explore here how to and when to avoid pitfalls.
First, I would like to explain when more than one thread is running in your application and they both want to access the same object. There is a number of ways one can achieve synchronisation. We will explore simple concept here.
Java provides a volatile keyword. Which provides happen before a relationship. which means for readability it is always there and acts as it is enclosed in the synchronized block. This variable is never cached and reads and writes goes straight through memory.
In Java 5 the volatile guarantees that volatile variables are written into the main memory and not just the cache memory for reading and writing purposes.
The Java volatile variable guarantees visibility.
example public volatile short index =0;
Now the complexity, if suppose write thread is incrementing the index and read thread is reading index then for reading thread index will be available before write thread has incremented it.
Example write thread sets the index to 2 and read thread reads at the same time, then read thread will read 1 as happened before. The Java volatile happens-before Guarantees.
Please note index++, index — , ++index and — index will not grantee atomicity and will give unpredictable results. Must be handled with care.
The volatile keyword is guaranteed to work on 32 bit and 64 variables.
The volatile keyword should be used with care and understand the full consequences, if volatile is set on the object it means its address is volatile but any deep contents are not synchronized.
Similarly, if an array is declared as a volatile, the only pointing object will be volatile and not the array itself. A simple example where it's mainly used will be boolean, short, char, float and similar type of variables.
Please see other articles coming on synchronisation.
Similarly, Business Integration Software provides sets of synchronisation techniques for Online Exam Software.
Assessment Management Software
Multiple Choice Question Software