Synchronized Block in java
Synchronized methods synchronize entire method. But sometimes, this is not what we want. A method may be 50 or 100 lines long, but only 3 lines out of them are required to be synchronized. In such a case, synchronizing the entire method will result in slowness of the system. Therefore, java provides a way known as ‘synchronized block’.
In synchronized block, we can synchronize only a block of code. This block can be as small as a single line of code to as big as n number of lines. This is a better solution than synchronized method.
Syntax
synchronized( lockObject ) {
//some code
}
Synchronized block example
package com.javatrainingschool;
public class Number {
public void displayNumbers() {
System.out.println(Thread.currentThread().getName() + " : Entering displayNumbers method");
System.out.println(Thread.currentThread().getName() + " : This is the second statement");
synchronized (this) {
for (int i = 0; i < 5; i++)
System.out.println(Thread.currentThread().getName() + " : " + i);
}
System.out.println(Thread.currentThread().getName() + " : Existing displayNumbers method");
}
}
package com.javatrainingschool;
public class Task implements Runnable {
private Number number;
public Task(Number number) {
this.number = number;
}
@Override
public void run() {
number.displayNumbers();
}
}
Main Class – NumberTest
package com.multithreading.synchronization;
public class NumberTest {
public static void main(String[] args) {
Number num = new Number();
Runnable task = new Task(num);
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
Thread t3 = new Thread(task);
t1.start();
t2.start();
t3.start();
}
}
In the below output, you can observe that only those statements are synchronized which are inside the synchronized block.
Sample output

Example 2
package com.javatrainingschool;
public class Calculation {
public void sum(int i) {
synchronized(this) { //this represents the object that invokes this method
System.out.println(Thread.currentThread().getName() + " : sum = " + (i + i));
}
}
public void square(int j) {
synchronized(this) {
System.out.println(Thread.currentThread().getName() + " : square = " + j*j);
}
}
}
package com.javatrainingschool;
public class SynchronizedBlockExample implements Runnable {
Calculation calculation;
public SynchronizedBlockExample(Calculation calculation) {
super();
this.calculation = calculation;
}
@Override
public void run() {
calculation.sum(4);
calculation.square(6);
}
public static void main(String[] args) {
Calculation calculation = new Calculation();
Runnable rt1 = new SynchronizedBlockExample(calculation);
Runnable rt2 = new SynchronizedBlockExample(calculation);
Runnable rt3 = new SynchronizedBlockExample(calculation);
Thread t1 = new Thread(rt1, "thread-a");
Thread t2 = new Thread(rt2, "thread-b");
Thread t3 = new Thread(rt3, "thread-c");
t1.start();
t2.start();
t3.start();
}
}
Output :
thread-a : sum = 8
thread-a : square = 36
thread-c : sum = 8
thread-c : square = 36
thread-b : sum = 8
thread-b : square = 36
- Home
- Java
- Java Fundamentals
- What is Java
- History of Java
- Java Version History
- Local Environment Set-up
- First Java Program
- How to set ‘Path’ env variable
- JDK, JRE, and JVM
- Object Oriented Programming
- Java Data Types
- Classes in Java
- Objects in Java
- Interfaces in java
- Class attributes and methods
- Methods In Java
- Variables and Constants in Java
- Java packages and Imports
- Access Modifiers In Java
- Java Operators
- Constructors in Java
- Control Statements – If else
- Control Statements – Loops
- Arrays in Java
- Java Abstraction
- Java Inheritance
- Polymorphism
- Java Exception Handling
- Strings in Java
- File IO
- Java Miscellaneous
- Design Patterns
- Java Fundamentals
- Collections
- Multithreading
- Java New Features
- Servlet
- JSP
- Spring
- Spring-Introduction
- First Spring Application
- Setter Injection
- Constructor injection
- Spring annotations
- Autowiring
- @Autowired Annotation Spring
- Spring MVC
- Spring JdbcTemplate
- Spring jdbcTemplate with MySQL
- Spring AOP
- Spring AOP Examples
- Various pointcut expressions in Spring AOP
- Download and configure Tomcat server
- Hibernate
- Architecture
- Hibernate Example
- First Hibernate Application (using xml configuration)
- First Hibernate Application (using annotations)
- JPA/HB – annotations
- Hibernate Identifiers
- Hibernate Generator Classes
- Save vs saveOrUpdate vs persist in Hibernate
- Inheritance Mapping in Hibernate
- Inheritance Mapping using annotations
- Hibernate Mapping
- Hibernate Query Language (HQL)
- HCQL Hibernate Criteria Query Language
- Hibernate Named Query
- Hibernate Caching
- Second Level Cache
- Spring Boot
- Spring Boot Basics
- Spring Boot Web
- Spring Boot Exception Handling
- Service discovery using Netflix Eureka
- Springboot OpenAPI/Swagger3
- Zuul Proxy Server + Routing
- Spring Cloud Gateway
- Spring Boot Security
- Circuit Breaker using Spring Boot Hystrix
- Interservice Communication
- Spring Boot Hateoas Links Example
- Lombok api
- Spring Boot with Mongo DB
- Load Balancer in Springboot
- Spring Boot Testing
- Spring Web Flux
- Database
- Web Service
- HTML
- Blog & Programs
- Docker
- Trainings
- Home
- Java
- Java Fundamentals
- What is Java
- History of Java
- Java Version History
- Local Environment Set-up
- First Java Program
- How to set ‘Path’ env variable
- JDK, JRE, and JVM
- Object Oriented Programming
- Java Data Types
- Classes in Java
- Objects in Java
- Interfaces in java
- Class attributes and methods
- Methods In Java
- Variables and Constants in Java
- Java packages and Imports
- Access Modifiers In Java
- Java Operators
- Constructors in Java
- Control Statements – If else
- Control Statements – Loops
- Arrays in Java
- Java Abstraction
- Java Inheritance
- Polymorphism
- Java Exception Handling
- Strings in Java
- File IO
- Java Miscellaneous
- Design Patterns
- Java Fundamentals
- Collections
- Multithreading
- Java New Features
- Servlet
- JSP
- Spring
- Spring-Introduction
- First Spring Application
- Setter Injection
- Constructor injection
- Spring annotations
- Autowiring
- @Autowired Annotation Spring
- Spring MVC
- Spring JdbcTemplate
- Spring jdbcTemplate with MySQL
- Spring AOP
- Spring AOP Examples
- Various pointcut expressions in Spring AOP
- Download and configure Tomcat server
- Hibernate
- Architecture
- Hibernate Example
- First Hibernate Application (using xml configuration)
- First Hibernate Application (using annotations)
- JPA/HB – annotations
- Hibernate Identifiers
- Hibernate Generator Classes
- Save vs saveOrUpdate vs persist in Hibernate
- Inheritance Mapping in Hibernate
- Inheritance Mapping using annotations
- Hibernate Mapping
- Hibernate Query Language (HQL)
- HCQL Hibernate Criteria Query Language
- Hibernate Named Query
- Hibernate Caching
- Second Level Cache
- Spring Boot
- Spring Boot Basics
- Spring Boot Web
- Spring Boot Exception Handling
- Service discovery using Netflix Eureka
- Springboot OpenAPI/Swagger3
- Zuul Proxy Server + Routing
- Spring Cloud Gateway
- Spring Boot Security
- Circuit Breaker using Spring Boot Hystrix
- Interservice Communication
- Spring Boot Hateoas Links Example
- Lombok api
- Spring Boot with Mongo DB
- Load Balancer in Springboot
- Spring Boot Testing
- Spring Web Flux
- Database
- Web Service
- HTML
- Blog & Programs
- Docker
- Trainings
- Home
- Java
- Java Fundamentals
- What is Java
- History of Java
- Java Version History
- Local Environment Set-up
- First Java Program
- How to set ‘Path’ env variable
- JDK, JRE, and JVM
- Object Oriented Programming
- Java Data Types
- Classes in Java
- Objects in Java
- Interfaces in java
- Class attributes and methods
- Methods In Java
- Variables and Constants in Java
- Java packages and Imports
- Access Modifiers In Java
- Java Operators
- Constructors in Java
- Control Statements – If else
- Control Statements – Loops
- Arrays in Java
- Java Abstraction
- Java Inheritance
- Polymorphism
- Java Exception Handling
- Strings in Java
- File IO
- Java Miscellaneous
- Design Patterns
- Java Fundamentals
- Collections
- Multithreading
- Java New Features
- Servlet
- JSP
- Spring
- Spring-Introduction
- First Spring Application
- Setter Injection
- Constructor injection
- Spring annotations
- Autowiring
- @Autowired Annotation Spring
- Spring MVC
- Spring JdbcTemplate
- Spring jdbcTemplate with MySQL
- Spring AOP
- Spring AOP Examples
- Various pointcut expressions in Spring AOP
- Download and configure Tomcat server
- Hibernate
- Architecture
- Hibernate Example
- First Hibernate Application (using xml configuration)
- First Hibernate Application (using annotations)
- JPA/HB – annotations
- Hibernate Identifiers
- Hibernate Generator Classes
- Save vs saveOrUpdate vs persist in Hibernate
- Inheritance Mapping in Hibernate
- Inheritance Mapping using annotations
- Hibernate Mapping
- Hibernate Query Language (HQL)
- HCQL Hibernate Criteria Query Language
- Hibernate Named Query
- Hibernate Caching
- Second Level Cache
- Spring Boot
- Spring Boot Basics
- Spring Boot Web
- Spring Boot Exception Handling
- Service discovery using Netflix Eureka
- Springboot OpenAPI/Swagger3
- Zuul Proxy Server + Routing
- Spring Cloud Gateway
- Spring Boot Security
- Circuit Breaker using Spring Boot Hystrix
- Interservice Communication
- Spring Boot Hateoas Links Example
- Lombok api
- Spring Boot with Mongo DB
- Load Balancer in Springboot
- Spring Boot Testing
- Spring Web Flux
- Database
- Web Service
- HTML
- Blog & Programs
- Docker
- Trainings