Synchronized Keyword in Java
Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from different threads' access. Using synchronized blocks, Java offers a synchronization technique.
We state that the synchronized keyword is used by every synchronized block in Java. A block that has the synchronized keyword in its declaration guarantees that only one thread is running at any given time. Until the thread inside the synchronized block has finished running and left the block, no other threads may enter it.
Java's synchronization feature allows for the management of multiple threads' access to any shared resource. Multiple threads trying to access the same resources in multi-threaded software may frequently result in unexpected and incorrect outcomes. Java offers a method for setting up threads and synchronizing their operations with the aid of synchronized blocks.
In Java, synchronized blocks are designated using the keyword synchronized. A synchronized block in Java is one that is connected to an object. Only one thread can be running at a time inside synchronized blocks since they are all synchronized on the same object. All other threads attempting to enter the synchronized block are stopped until the thread inside the block departs the block. The idea of monitors is used to do this. Each Java object has a monitor attached to it that a thread can lock or unlock.
The synchronized blocks feature of the Java programming language offers a very practical method of generating threads and coordinating their work. The synchronized statement's broad form is provided below.
Syntax:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
We will now demonstrate printing a counter utilizing two distinct threads in two different scenarios.
Use of Synchronized in Java
The Java synchronized keyword is used because it facilitates several concurrent programming-related tasks. The following are some of the synchronized keyword's important characteristics:
- Java's synchronized keyword offers the locking feature, ensuring that there are no race conditions between threads (or)To prevent thread interference
- The program statements cannot be rearranged thanks to the synchronized keyword (or) to prevent consistency problem.
- Locking and unlocking are provided via the synchronized keyword. Before entering the synchronized block, the thread must acquire the lock.
Types of Synchronizations
There are two typed of synchronizations in java.
- Process Synchronization
- Thread Synchronization
Thread Synchronization:
The subroutine that can run independently within a single process is referred to as a thread. Multiple threads may be contained within a single process, and the process may schedule all of the threads for a crucial resource. A single thread can have numerous children.
Thread synchronization can be divided into two categories: inter-thread communication and mutual exclusion.
- Mutual Exclusive: Mutual exclusivity keeps threads from interfering with one another while sharing data. There are three different ways to do it:
- By Using Synchronized method.
- By Using Synchronized block.
- By Using Static synchronization.
- Cooperation (Inter-thread communication in java).
Concept of Lock in Java:
An internal object known as the lock or monitor is an essential part of synchronization. Each object has a lock attached to it. Since Java 5, there are various lock implementations in the java. util. concurrent. locks package.
Process Synchronization
Process synchronization is the sharing of resources among two or more processes while concurrently ensuring data consistency. The Critical Section in a programming language is the portion of code that is used by many different processes. Although there is other strategies, such as Peterson's Method, for avoiding critical section issues, semaphores are by far the most popular one. Multiple threads trying to access the same resources in multi-threaded software may frequently result in unexpected and incorrect outcomes.
Java offers a method for setting up threads and synchronizing their operations with the aid of synchronized blocks.
Understanding the problem without synchronization:
This sample lacks synchronization, resulting in inconsistent output. Here's an illustration:
class Tab{
void printTab(int a) {//not included synnhronization method
for(int j=1;j<=5;j++){
System.out.println(a*j);
Try{
Thread.sleep(200);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyTh1 extends Th{
Table p;
MyTh1(Table p){
this.p=p;
}
public void run(){
p. printTable(5);
}
}
class MyTh2 extends Th{
Table p;
MyTh2(Table p){
this. p=p;
}
public void run(){
p.printTable(100);
}
}
class TestSynchro 1{
public static void main(String args[]){
Tab jg = new Tab();//only one object
MyTh1 p1=new MyTh1(jg);
MyTh2 p2=new MyTh2(jg);
p1.start();
p2. start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
Java Synchronized Method
Any method is referred to as a synchronized method if you declare it to be so. Locking an object for any shared resource involves using a synchronized method.
A thread automatically gets the lock for an object when it calls a synchronized method, and it releases the lock after the thread has finished its work.
class Tab{
synchronized void printTable(int d){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(d*i);
Try{
Thread.sleep(400);
} catch (Exception e){System.out.println(e);}
}
}
}
class MyTh1 extends Th {
Table p;
MyTh1(Table p){
this. p=p;
}
public void run (){
p. printTable (5);
}
}
class MyTh2 extends Th{
Table p;
MyTh2(Table p){
this. p=p;
}
public void run (){
p. printTable (100);
}
}
public class TestSynchr2{
public static void main(String s[]){
Tab bj = new Tab();//only one object
MyTh1 p1=new MyTh1(bj);
MyTh2 p2=new MyTh2(bj);
p1.Start();
p2.Start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
A whole procedure does not necessarily need to be synchronized. Sometimes synchronizing just, a portion of a process is ideal. This is made feasible via Java synchronized blocks inside of methods.
Need for synchronized in Java
The Java synchronized keyword is used because it facilitates a few concurrent programming-related tasks. The following are some of the synchronized keyword's important characteristics:
- Java's synchronized keyword offers the locking feature, ensuring that there are no race conditions between threads.
- The program statements cannot be rearranged thanks to the synchronized keyword.
- Locking and unlocking are provided via the synchronized keyword. Before entering the synchronized block, the thread must acquire the lock.
It flushes the write operation after reading the data, and then releases the lock. The Java language uses a concept known as monitors to perform this synchronization. At any given time, a monitor can only be owned by one thread. A thread is considered to have entered the monitor when it obtains a lock. Until the initial thread quits the locked monitor, any subsequent attempts to do so will be blocked.
Important Points of Synchronized keyword in Java
- Java's synchronized keyword makes sure that only one thread at a time can access shared data.
- Only a block or a function can be made synchronized using the Java synchronized keyword.
- When a thread enters a synchronized block, it obtains a lock. The thread also releases the lock after leaving that procedure.
- We risk receiving a NullPointerException if we attempt to use a null object in the synchronized block.
- We are unable to use more than one JVM to offer access control to a shared resource using the Java synchronized keyword.
- Because the synchronized keyword operates slowly, the system performance may suffer.
- Using the Java synchronized block is preferable to using the Java synchronized method.
- Deadlock or starvation may come from improper synchronization implementation in our code.
- In Java, using a synchronized keyword with the function Object () {[native code]} is prohibited. Additionally, in Java, the synchronized keyword cannot be used with variables.
- The Object class's wait (), notify (), and notifyAll methods are some crucial ones that we might employ to establish synchronization in Java ().
Conclusion
In this Java post, we covered various approaches to synchronization using the synchronized keyword. It can either be used alongside methods or inside a method block. In this short post, we looked at various approaches of achieving thread synchronization using the synchronized keyword.
Additionally, we discovered how a race condition may affect our program and how synchronization can help us prevent it. See our page on java. util.concurrent.Locks for additional information regarding Java's use of locks for thread safety.
We looked at the necessity of Java synchronization. Finally, we went over each application of a synchronized term with an example to assist you understand.