In Java, a Synchronized block helps in performing synchronization on any particular resource of the function or method. If there are 100 lines of code(LOC) and synchronization has to be done for only 10 lines, then a synchronized block can be used. Synchronized can be used as keyword, method and blocks. In this tutorial, we will discuss the synchronized block in detail.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
The syntax of the synchronized block is as shown below:
Synchronized( lo) { //statements that have to be synchronized }
Here, lo is the lock object
As already discussed, the Synchronized block helps in performing synchronization on any particular resource of the function or method. When a thread needs to execute lines that are synchronized inside the synchronized block, it is mandatory toacquire the lock on the monitor of the lock Object lo mentioned in the syntax above. At a time, only 1 thread can acquire the lock object’s monitor. Each thread has to wait until the thread that currently holds the lock completes the execution and releases it.
Similarly, synchronized keyword assures that at a time, only 1 thread will be executing the lines of code in a synchronized block, which in turn prevents more than one thread from corrupting the data which is shared within the block.
Suppose a method consists of500 LOC(lines of code), but there exist only 20 lines of code that holds a critical section(CS) of code. That is, these 20 lines can alter or change the state of the object. So synchronization can be done to these 20 lines of code function to avoid any alteration in object state and make sure that other threads execute the other 480 lines within the particular method without any intermission.
Now, let us see some sample programs on the synchronized block in Java.
Java program to implement synchronized block
Code:
class Testsmple{ void printTestsmple(int n) { //start of synchronized block synchronized(this) { System.out.println("The output of synchronized block is: "); for( int i=1 ; i<=4 ; i++ ) { System.out.println(n*i); //exception handling try { Thread.sleep(500); } catch(Exception exc) { System.out.println(exc) ; } } } } //end } class T1 extends Thread { Testsmple t; T1(Testsmple t) { this.t=t; } public void run() { t.printTestsmple(10); } } class T2 extends Thread { Testsmple t; T2(Testsmple t) { this.t=t; } public void run() { t.printTestsmple(200); } } public class SyncBlockExample { public static void main(String args[]) { // create only one object Testsmple ob = new Testsmple(); //objects of threads T1 t1=new T1(ob); T2 t2=new T2(ob); //start the threads t1 and t2 t1.start(); t2.start(); } }
Output:
In this program, two threads t1 and t2, are used where each of them has a method printTestsmple that calls the synchronized method. The thread 1 input for printTestsmple is 10, and the thread 2 input is 200. In the result, it can be seen that the output of the synchronized block of the first thread is 10, 20, 30, 40. At the same time, the result of the thread 2 synchronized block is 200, 400, 600, 800. Moreover, there is a line “The output of the synchronized block is:” which gets printed between each thread’s result.
Java program to implement synchronized blocks with the help of using anonymous class.
Code:
class Testsmple{ void printTestsmple(int n) { //start of synchronized block synchronized(this) { System.out.println("The output of synchronized block is: "); for( int i=1 ; i<=4 ; i++ ) { System.out.println(n*i); //exception handling try { Thread.sleep(500); } catch(Exception exc) { System.out.println(exc) ; } } } } //end } public class SyncBlockExample { //main method public static void main(String args[]) { //create only one object final Testsmple obj = new Testsmple() ; //create thread th1 Thread th1=new Thread() { public void run() { obj.printTestsmple(10) ; } } ; //create thread th2 Thread th2=new Thread() { public void run() { obj.printTestsmple(200); } } ; th1.start() ; th2.start() ; }}
Output:
In this program also, two threads t1 and t2, are used where each of them has a method printTestsmple that calls the synchronized method. The thread 1 input for printTestsmple is 10, and the thread 2 input is 200. In the result, it can be seen that the output of the synchronized block of the first thread is 10, 20, 30, 40. At the same time, the result of the thread 2 synchronized block is 200, 400, 600, 800. Moreover, there is a line “The output of the synchronized block is:” which gets printed between each thread’s result. The only difference is the presence of an anonymous class in this program.
Java program to implement synchronized block.
import java.util.*; class ABC { String nm = ""; public int cnt = 0; public void samplename(String stringexample, Listli) { // In order to change the name at a time, only 1 thread is permitted synchronized(this) { nm = stringexample; cnt++; } li.add(stringexample); } } public class SyncBlockExample { //main method public static void main (String[] args) { //create an object for the class ABC ABC obj = new ABC(); //create a list List li = new ArrayList (); //call the method using the object created obj.samplename("Anna Sam", li); System.out.println(obj.nm); } }
Output:
In this program, a class ABC is created with a synchronized method inside the method samplename. A string “Anna Sam” is passed as an input for calling the method samplename. On executing the code, the string “Anna Sam” gets printed.
Some of the advantages are given below:
The above is the detailed content of Synchronized Block in Java. For more information, please follow other related articles on the PHP Chinese website!