×

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

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.