Working with multi-threaded applications is a very complicated task in Java. Java developers usually have to keep various details into account while working with multi-threading. Various aspects, if not properly handled can disrupt the process.
Table of Contents
One such case is when multiple threads in a single program try to access the same resource at the same time. For instance, a thread attempting to open a file to read data while another thread is trying to close it.
Such concurrency issues often result in various unexpected results. In such situations, no thread can properly operate and this can also lead to data corruption.
To cater to that, the access to the resources must be limited to one thread at a time to prevent multiple threads from accessing the same resource at the same time. Java programming language came up with a solution by offering the mechanism of synchronization to avoid such concurrency. It provides synchronized thread access to all the shared resources.
In this article, we will be discussing the synchronized keyword in Java that is used to implement the synchronization in Java. We will also explore various ways to use the Java synchronized keyword with aid of coding examples.
The process of restricting multiple threads and allowing a single thread at a time to access the shared data is called Synchronization. Java offers the mechanism of synchronization for multi-threading using synchronized blocks.
A synchronized block is declared in Java using the synchronized keyword. The synchronized blocks ensure that only one thread will be executed at a particular time. It allows only one thread at a time and no other thread can enter that synchronized block until the thread inside the block completes its execution and leaves the block.
The code below demonstrates the general syntax for declaring a block using the synchronized keyword in Java:
1. synchronized( lockObj) 2. { 3. 4. // synchronized statements 5. 6. }
The lockObj used here is a reference to an object whose lock is related to the synchronized statements.
The use of the Java synchronized keyword actually marks the block or a method as synchronizing on a specific object.
Every Java object created Inside the JVM, along with every Class that is loaded, gets an associated lock to prevent any other thread to access the resource.
After the Java synchronized keyword is applied on a block or a method, the active thread acquires the lock on the specified object before starting the execution of the code.
The lock is then released afterward either when the code execution finishes or either the thread is temporarily suspended.
Between the process of acquiring the lock and releasing it, a thread actually “owns” the lock. It means that other threads will have to wait to acquire the lock until the currently running thread does not release it.
This locking mechanism plays the primary role to prevent concurrency as due to this acquiring and releasing process, multiple threads will never get access at the same time.
The Java synchronization can be classified into the following two types:
Process Synchronization refers to the mechanism of sharing the resources between two or more processes while keeping checks for any inconsistencies in data.
The piece of code that is shared among different processes is often referred to as the Critical Section. There have been many solutions proposed to avoid this critical section problem. Among all the proposed solutions, the most popular way and widely used one is the Semaphores method.
The concurrent execution of the critical resource multiple threads is referred to as the thread Synchronization. Thread is a subroutine that can execute independently within a process. A single process can have multiple threads and the process can also schedule all the threads for a resource making it a critical resource.
When a synchronized block is used with the instance methods, each object gets its synchronized method. There will be only one thread for each object, that can be executed inside the method. If there is more than one object, then only one thread will be executed inside the block for each object.
See this code demonstration below:
1. public class myCounter { 2. private int counter = 0; 3. public synchronized void incrementCounter(int num) { 4. this.counter += num; 5. } 6. public synchronized void decrementCounter(int num) { 7. this.counter -= num; 8. } 9. }
A Static method can also be marked as synchronized just like an instance method is marked using the synchronized keyword in Java.
Below is another code demonstration showing the working of a Java synchronized static method:
1. public static MyCounter { 2. private static int counter = 0; 3. public static synchronized void incrementCounter(int num) { 4. counter += num; 5. } 6. }
Instead of synchronizing the whole method, you can also just synchronize a particular block inside the method using the Java synchronized keyword.
See this synchronized block of Java code inside an unsynchronized Java method:
1. public void incrementCounter(int num) { 2. synchronized(this) { 3. this.counter += num; 4. } 5. }
A Synchronized blocks can also be used inside a static method.
Below is the code showing the use of a synchronized block inside the static method:
1. public class DemoClass { 2. public static void OutputMessage(String textMessage) { 3. synchronized(DemoClass.class) { 4. log.writeln(textMessage); 5. } 6. } 7. }
The Java synchronized keyword is extremely important as it is used for almost all activities related to multithreaded programming.
We also do not have any alternative for many of its notable features such as:
It is certain that the synchronized keyword in Java is majorly responsible for concurrency in multithreaded applications but there are some very important points to be considered while using the Java synchronized keyword,
Considering all these points, it might seem that using the Java synchronized keyword is not such a treat. Using it can be a bit tricky especially if you are new and not completely sure of know what you are doing. Considering that, it is a better option to use the Java synchronized method instead of the Java synchronized keyword, at least until do not become good enough.
Multithreading is known for one of the most difficult areas of Java. It’s true. Concurrent programming is not very easy to learn but some decent understanding of multithreading and synchronization can be an excellent addition to your Java toolkit.
In this article, we discussed numerous ways of using the Java synchronized keyword to achieve synchronization in a multi-threaded application.
Related Article: How to use Java Generic Interface
We also covered every way of using the Java synchronized keyword with the aid of some examples. Guide to the Synchronized Keyword in Java
Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use