Synchronization in Java

Last updated on Dec 29 2022
Prabhas Ramanathan

Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Table of Contents

Why use Synchronization

The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object’s fields has to acquire the object’s lock before accessing them, and then release the lock when it’s done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.

Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let’s see the example:

1. class Table{ 
2. void printTable(int n){//method not synchronized 
3. for(int i=1;i<=5;i++){ 
4. System.out.println(n*i); 
5. try{ 
6. Thread.sleep(400); 
7. }catch(Exception e){System.out.println(e);} 
8. } 
9. 
10. } 
11. } 
12. 
13. class MyThread1 extends Thread{ 
14. Table t; 
15. MyThread1(Table t){ 
16. this.t=t; 
17. } 
18. public void run(){ 
19. t.printTable(5); 
20. } 
21. 
22. } 
23. class MyThread2 extends Thread{ 
24. Table t; 
25. MyThread2(Table t){ 
26. this.t=t; 
27. } 
28. public void run(){ 
29. t.printTable(100); 
30. } 
31. } 
32. 
33. class TestSynchronization1{ 
34. public static void main(String args[]){ 
35. Table obj = new Table();//only one object 
36. MyThread1 t1=new MyThread1(obj); 
37. MyThread2 t2=new MyThread2(obj); 
38. t1.start(); 
39. t2.start(); 
40. } 
41. }

Output: 5
100
10
200
15
300
20
400
25
500

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

1. //example of java synchronized method 
2. class Table{ 
3. synchronized void printTable(int n){//synchronized method 
4. for(int i=1;i<=5;i++){ 
5. System.out.println(n*i); 
6. try{ 
7. Thread.sleep(400); 
8. }catch(Exception e){System.out.println(e);} 
9. } 
10. 
11. } 
12. } 
13. 
14. class MyThread1 extends Thread{ 
15. Table t; 
16. MyThread1(Table t){ 
17. this.t=t; 
18. } 
19. public void run(){ 
20. t.printTable(5); 
21. } 
22. 
23. } 
24. class MyThread2 extends Thread{ 
25. Table t; 
26. MyThread2(Table t){ 
27. this.t=t; 
28. } 
29. public void run(){ 
30. t.printTable(100); 
31. } 
32. } 
33. 
34. public class TestSynchronization2{ 
35. public static void main(String args[]){ 
36. Table obj = new Table();//only one object 
37. MyThread1 t1=new MyThread1(obj); 
38. MyThread2 t2=new MyThread2(obj); 
39. t1.start(); 
40. t2.start(); 
41. } 
42. }

Output: 5
10
15
20
25
100
200
300
400
500

Example of synchronized method by using annonymous class

In this program, we have created the two threads by annonymous class, so less coding is required.

1. //Program of synchronized method by using annonymous class 
2. class Table{ 
3. synchronized void printTable(int n){//synchronized method 
4. for(int i=1;i<=5;i++){ 
5. System.out.println(n*i); 
6. try{ 
7. Thread.sleep(400); 
8. }catch(Exception e){System.out.println(e);} 
9. } 
10. 
11. } 
12. } 
13. 
14. public class TestSynchronization3{ 
15. public static void main(String args[]){ 
16. final Table obj = new Table();//only one object 
17. 
18. Thread t1=new Thread(){ 
19. public void run(){ 
20. obj.printTable(5); 
21. } 
22. }; 
23. Thread t2=new Thread(){ 
24. public void run(){ 
25. obj.printTable(100); 
26. } 
27. }; 
28. 
29. t1.start(); 
30. t2.start(); 
31. } 
32. }

Output: 5
10
15
20
25
100
200
300
400
500

Synchronized Block in Java

Synchronized block can be used to perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

• Synchronized block is used to lock an object for any shared resource.
• Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

1. synchronized (object reference expression) { 
2. //code block 
3. }

Example of synchronized block

Let’s see the simple example of synchronized block.

Program of synchronized block

1. class Table{ 
2. 
3. void printTable(int n){ 
4. synchronized(this){//synchronized block 
5. for(int i=1;i<=5;i++){ 
6. System.out.println(n*i); 
7. try{ 
8. Thread.sleep(400); 
9. }catch(Exception e){System.out.println(e);} 
10. } 
11. } 
12. }//end of the method 
13. } 
14. 
15. class MyThread1 extends Thread{ 
16. Table t; 
17. MyThread1(Table t){ 
18. this.t=t; 
19. } 
20. public void run(){ 
21. t.printTable(5); 
22. } 
23. 
24. } 
25. class MyThread2 extends Thread{ 
26. Table t; 
27. MyThread2(Table t){ 
28. this.t=t; 
29. } 
30. public void run(){ 
31. t.printTable(100); 
32. } 
33. } 
34. 
35. public class TestSynchronizedBlock1{ 
36. public static void main(String args[]){ 
37. Table obj = new Table();//only one object 
38. MyThread1 t1=new MyThread1(obj); 
39. MyThread2 t2=new MyThread2(obj); 
40. t1.start(); 
41. t2.start(); 
42. } 
43. }

 

Output:5
10
15
20
25
100
200
300
400
500

 

Same Example of synchronized block by using annonymous class:

//Program of synchronized block by using annonymous class

1. class Table{ 
2. 
3. void printTable(int n){ 
4. synchronized(this){//synchronized block 
5. for(int i=1;i<=5;i++){ 
6. System.out.println(n*i); 
7. try{ 
8. Thread.sleep(400); 
9. }catch(Exception e){System.out.println(e);} 
10. } 
11. } 
12. }//end of the method 
13. } 
14. 
15. public class TestSynchronizedBlock2{ 
16. public static void main(String args[]){ 
17. final Table obj = new Table();//only one object 
18. 
19. Thread t1=new Thread(){ 
20. public void run(){ 
21. obj.printTable(5); 
22. } 
23. }; 
24. Thread t2=new Thread(){ 
25. public void run(){ 
26. obj.printTable(100); 
27. } 
28. }; 
29. 
30. t1.start(); 
31. t2.start(); 
32. } 
33. }

 

Output:5
10
15
20
25
100
200
300
400
500

Static Synchronization

If you make any static method as synchronized, the lock will be on the class not on object.

java 125

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.

Example of static synchronization

In this example we are applying synchronized keyword on the static method to perform static synchronization.

1. class Table{ 
2. 
3. synchronized static void printTable(int n){ 
4. for(int i=1;i<=10;i++){ 
5. System.out.println(n*i); 
6. try{ 
7. Thread.sleep(400); 
8. }catch(Exception e){} 
9. } 
10. } 
11. } 
12. 
13. class MyThread1 extends Thread{ 
14. public void run(){ 
15. Table.printTable(1); 
16. } 
17. } 
18. 
19. class MyThread2 extends Thread{ 
20. public void run(){ 
21. Table.printTable(10); 
22. } 
23. } 
24. 
25. class MyThread3 extends Thread{ 
26. public void run(){ 
27. Table.printTable(100); 
28. } 
29. } 
30. 
31. 
32. 
33. 
34. class MyThread4 extends Thread{ 
35. public void run(){ 
36. Table.printTable(1000); 
37. } 
38. } 
39. 
40. public class TestSynchronization4{ 
41. public static void main(String t[]){ 
42. MyThread1 t1=new MyThread1(); 
43. MyThread2 t2=new MyThread2(); 
44. MyThread3 t3=new MyThread3(); 
45. MyThread4 t4=new MyThread4(); 
46. t1.start(); 
47. t2.start(); 
48. t3.start(); 
49. t4.start(); 
50. } 
51. }

 

Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

 

Same example of static synchronization by annonymous class

In this example, we are using annonymous class to create the threads.

1. class Table{ 
2. 
3. synchronized static void printTable(int n){ 
4. for(int i=1;i<=10;i++){ 
5. System.out.println(n*i); 
6. try{ 
7. Thread.sleep(400); 
8. }catch(Exception e){} 
9. } 
10. } 
11. } 
12. 
13. public class TestSynchronization5 { 
14. public static void main(String[] args) { 
15. 
16. Thread t1=new Thread(){ 
17. public void run(){ 
18. Table.printTable(1); 
19. } 
20. }; 
21. 
22. Thread t2=new Thread(){ 
23. public void run(){ 
24. Table.printTable(10); 
25. } 
26. }; 
27. 
28. Thread t3=new Thread(){ 
29. public void run(){ 
30. Table.printTable(100); 
31. } 
32. }; 
33. 
34. Thread t4=new Thread(){ 
35. public void run(){ 
36. Table.printTable(1000); 
37. } 
38. }; 
39. t1.start(); 
40. t2.start(); 
41. t3.start(); 
42. t4.start(); 
43. 
44. } 
45. }

 

Output: 1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

 

Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class name .class. A static synchronized method printTable(int n) in class Table is equivalent to the following declaration:

1. static void printTable(int n) { 
2. synchronized (Table.class) { // Synchronized block on class A 
3. // ... 
4. } 
}

So, this brings us to the end of blog. This Tecklearn ‘Synchronization in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Synchronization in Java"

Leave a Message

Your email address will not be published. Required fields are marked *