In my previous article, I explained usages of volatile keyword in Java, but some time for right synchronization just volatile keyword may not be sufficient. I will explain the usages of Java synchronized keyword in this article.
In the previous example, we used a short index variable where we can set and reset the values. How about using incremental, decremental, post and pre incremental and decremental. This will not work with with the just volatile keyword.
example
public volatile short index =0;
if two threads want to perform index++ and index — , what will be the consequence. Lets first clarify index++ and index — as follows:
index = index + 1; // Equivalent of index++
index = index — 1; // Equivalent of index —
Now on the outset, it appears simple but how CPU performs internal varies from CPU to CPU. The volatile keywords function effectively when the operation is being performed in a single CPU cycle. here in our example, it will take more than one CPU cycle. Hence we need a solution which guarantees automaticity.
Java has keyword synchronized which can be used to help us here.
We can rewrite our example as follows:
synchronized {
index++;
}
synchronized {
index — ;
}
This will guarantee us atomicity and index will be synchronized correctly in the multi-threaded application. I will cover the synchronized keyword in part 3 of the Java Synchronization article.
Similarly, Business Integration Software provides sets of synchronisation techniques for automaticity in our Online Exam Software.
Assessment Management Software
Multiple Choice Question Software