×

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by sharing access and the object references.

In the Java programming language, there are two types of synchronization they are:

  • Method Synchronization.
  • Block Synchronization (Statement Synchronization).

The execution of the thread enters into synchronized block or method, then that block or method acquires lock until the task is completed.

 The Synchronized methods run very slowly thus it reduces the performance of the program. It is recommended to use the synchronized method only when it is at most necessary. The Synchronization throw the null pointer exception when object is null in synchronized block.

Method Synchronization:

Method Synchronization is the process in that the object can able to visible to multiple threads. These threads can perform the read or write operations on the object. The Method Synchronization is used to overcome the problems of “thread interference” and “memory consistency” which raised by the normal communication between thread by the shared access to fields.

In the method synchronization, if one thread is invoked for execution in the synchronized method then other threads should wait until the initial thread completes its work.

Example program:

import java.io.*;
/*example program for accessing more than one thread to same object without synchronization*/
class Sync
{
public void getLine()
{
for(int i=0; i<3;i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}


}
}
}
class Method extends Thread
{
/*creating reference for Sync object*/
Sync sy;
Method (Sync sy)
{
sy.getLine();
}
public void run()
{
sy.getLine();
}
} 
class Main
{
public static void main(String args[])
{
/*object of the Sync class shared among threads*/
Sync ob = new Sync();
/*creating the threads that shares same object*/
Method m1 = new Method (ob);
Method m2 = new Method (ob);
/*Execution of the threads start*/
m1.start();
m2.start();
}
}

Output:

0
1
2
0
1
2

In the above program, the two thread are accessing the same object at the same time. So there is a chance of occurring the collision. To avoid the collision, the method synchronization is used

Example program:

import java.io.*;
class Sync 
{
synchronized public void getLine()
{
for(int i=0; i<3;i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}


class Method extends Thread
{
Sync sy;
Method (Sync sy)
{
this.sy= sy;
}
public void run()
{
sy.getLine();
}
}


class Main
{
public static void main (String args[])
{
/*object of the Sync class shared among threads*/
Sync ob = new Sync();
/*creating the threads that shares same object*/
Method m1 = new Method (ob);
Method m2 = new Method (ob);
/*Execution of the threads start*/
m1.start();
m2.start();


}
}

Output:

0
1
2
0
1
2

Block Synchronization:

The Block synchronization is the process of accessing the limited number of lines of code in a Method. In other words, the block synchronization performs on the specific resource in method by the shared access.

For Example, Let’s assume that a method contains 30 lines of code but the only 10 of them are modifiable. So, these specific 10 lines of code are synchronized, only one thread can access at a time to avoid collision and remaining lines of code can execute by the other threads.

Example Program:

import java.io.*;
import java.util.*;


class Block
{
String name=””;
public int count=0;

public void display(String str, List<String> list)
{
synchronized(this)
{
name = str;
count++;
}
list.add(str);
}
}


class Main
{
public static void main(String args[])
{
Block b = new Block();
List<String> list = new ArrayList<String>();
b.display(“Rahul”,list);
System.out.println(b.name);
}
}

Output:

Rahul

Advantages:

  • By using the Synchronized methods, the multi-threading concept is achieved with shared resource.
  • By using the Synchronized methods, the both instance methods and static methods (Synchronized) can able to executed simultaneously.

Disadvantages:

  • The Synchronization methods decreases the efficiency because of the synchronized methods run slowly.
  • The Synchronization doesn’t allow the read operation simultaneously.

Summary:

The Synchronization in Java is the process of synchronizing the specific methods or statement to avoid the collision when executing the threads concurrently. In java there are two types of synchronization they are “Method Synchronization” and “Block Synchronization”. The Synchronization is used to avoid the problems like thread interference and memory consistency errors.


Related Topics

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.