Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Thread Synchronization in Java | Synchronized Method & Block

  • Chemical Properties of Matter (Element, Compound and Mixture)
    Chemical Properties of Matter examples (Element, Compound and Mixture) Science
  • Jagannath Rath Yatra History in Hindi | जगन्नाथ पुरी की कहानी
    Jagannath Rath Yatra History in Hindi | जगन्नाथ पुरी की कहानी Festival
  • Maharishi Valmiki in Hindi, Biography, Dacoit Ratnakar, Jayanti
    Maharishi Valmiki in Hindi, Biography, Dacoit Ratnakar, Jayanti Spiritual
  • Kishkindha Kand in Hindi | Ram meets Hanuman | किष्किंधा कांड
    Kishkindha Kand in Hindi | Ram meets Hanuman | किष्किंधा कांड Spiritual
  • Fundamental Duties of Indian Citizens
    Fundamental Duties of Indian Citizens | 11 मौलिक कर्तव्य हिंदी में General Knowledge
  • Diwali The Festival of Lights
    Diwali 2022, Indian Festival of Lights essay (दिवाली त्योहार पर निबंध, कहानी) Festival
  • Kishore Kumar Biography in Hindi | किशोर कुमार की जीवनी
    Kishore Kumar Biography in Hindi | किशोर कुमार की जीवनी Biography
  • Chhath Puja Story
    Chhath Puja History : क्यों मनाते हैं छठ महापर्व Festival

Thread Synchronization in Java | Synchronized Method & Block

Posted on September 2, 2021July 6, 2022 By GeekCer Education 2 Comments on Thread Synchronization in Java | Synchronized Method & Block
Importance of Thread Synchronization in Java

Thread synchronization in Java prevents a thread from accessing any shared resources being used by another thread. During the thread synchronization process, if thread T1 is working on object O1, we prohibit thread T2 from accessing object O1.

The “synchronized” modifier is used to establish synchronization. It only applies to methods and blocks; classes and variables are not included.

When we declare a method or block as synchronized, only one thread may execute it on the supplied object at a moment.

Table of Contents

  • Need of Thread Synchronization
  • Synchronized Method in Java for Thread Synchronization
  • Synchronized Block in Java for Thread Synchronization
  • Class Level lock
  • Class level lock in synchronized block
  • Thread communication in Java
  • notify() and notifyAll() methods
  • Thread Deadlock in java example
  • How to avoid deadlock in multithreading?
  • Daemon Thread in Java with example

Need of Thread Synchronization

Because several objects might act on the same item when working in a multithreading environment, there is a risk of data inconsistency. Thread synchronization is used to solve the problem of data inconsistency.

However, it may increase thread waiting time, which may have an impact on system performance. As a result, you should only use the synchronized keyword if you have a necessity.

When synchronization is used, one thread locks the object, preventing the second thread from accessing it until the first thread has exited.

Synchronized Method in Java for Thread Synchronization

When one thread runs a synchronized method on an object, the other thread is unable to execute a synchronized method on the same object. Non-synchronized methods, on the other hand, can be executed by other threads.


public synchronized void doWork() {

}

Synchronized Block in Java for Thread Synchronization

Declare those sections as synchronized when you need to synchronize a set of statements. The synchronized block minimizes the thread’s waiting time and enhances the system’s performance.

You may use synchronized block to lock the current object like follows:


synchronized (this) {

}

If you want to lock the any other object you can use synchronized block as follows:


synchronized (object) {

}

You can only use the synchronized block notion for classes and objects; if you use it for basic types, you’ll get a compile time error.

Class Level lock

A thread must have class level lock in order to run a static synchronized method. If a thread performs a static synchronized method, the remaining threads cannot execute any static synchronized method of the class at the same time. The following methods can be executed by the remaining threads:

  • Normal static methods
  • Normal Instance methods
  • Synchronized instance methods

Class level lock in synchronized block

To obtain class level lock, we may declare synchronized block as follows.


synchronized (<class-name>.class) {

}

Note: Synchronization is only useful when many threads are acting on the same object. If several threads act on numerous objects, synchronization has no impact. At the same moment, a thread can acquire several locks from distinct objects.

Thread communication in Java

We sometimes need to establish communication between two threads when programming. The wait(), notify(), and notify() methods are used to establish such communication. The thread that requires an update calls the wait() method, while the thread responsible for updating it calls the notify() method.

The wait(), notify(), and notify() methods are accessible in the Object class; if a thread wishes to use these methods, it must first acquire the object’s lock and be in the synchronized region.

These methods can only be called from a synchronized region; otherwise, an IllegalMonitorStateException will be thrown.

When a thread invokes the wait() method, the lock is instantly released and the thread is placed in the wait state. The thread releases just the current object’s locks, not all locks, when the notify() or notifyAll() methods are invoked. And also it won’t be able to release lock immediately.

notify() and notifyAll() methods

We can only notify one waiting thread with notify(), but we can’t predict which waiting thread will be alerted. The remaining threads will be held until further notification is received.

When notifyAll() is used, all waiting threads are notified , but they are executed one by one.

Thread Deadlock in java example

When one thread locks an object and waits for another thread to be freed by another object, and the second thread does the same, both threads will wait indefinitely. This is referred to as thread deadlock in Java.

In other words, a deadlock occurs when two threads are stuck waiting for each other indefinitely. Any further execution is halted and the software comes to a halt in the event of a thread deadlock.

How to avoid deadlock in multithreading?

How to solve deadlock in java? It is determined by the programming logic you create. There is no precise strategy for resolving the deadlock. You should be cautious when using the synchronized keyword in programming logic since synchronized keyword is the only source of deadlocks.

Daemon Thread in Java with example

JVM creates daemon threads, which operate in the background and provide services to others. The garbage collector, for example, is always running in the background, collecting unneeded objects and freeing up memory.

The primary goal of the daemon thread is to assist the non-daemon thread. You can change the Daemon nature just before to starting a thread. If you try to modify after starting a thread, you’ll get a “IllegalThreadStateException” runtime error.

Note: When the final non-daemon thread is terminated, all daemon threads will be killed automatically.

Recommended Articles

  • Oops concepts in java with examples
  • Difference between abstract Vs interface in java
  • Example program of exception handling in java
  • Agile methodology in software engineering
  • How to create project in maven project?

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java Tags:Life Cycle, Multithreading, Synchronization, Thread, Thread Safe

Post navigation

Previous Post: Multithreading in java, Thread, Runnable | Life Cycle of Thread
Next Post: Exception Handling in Java

More Related Articles

Jenkins java | Installing Jenkins on Windows Jenkins java | Installing Jenkins on Windows Important
Immutable class in Java Immutable class in Java | How to create Immutable class in Java Important
Java Switch Case Java Switch Case : Switch fall-through, default, break, examples Java
Java Keywords Java Keywords Java
Java Operators Java Operators Java
Fork/Join Framework in Java | RecursiveTask, RecursiveAction Fork/Join Framework in Java | RecursiveTask, RecursiveAction Java

Comments (2) on “Thread Synchronization in Java | Synchronized Method & Block”

  1. Scott says:
    September 8, 2021 at 9:23 am

    Good Job, Nice Article…

    Reply
  2. Pingback: Difference between StringBuffer and StringBuilder in Java - GeekCer

Leave a Reply Cancel reply

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

  • Java Home
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Keywords
  • Java Operators
  • Java If-else Statement
  • Java Switch
  • Java Loop
  • Java Arrays
  • Method Overloading in Java
  • Java OOP
  • Java Collections
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Multithreading in java
  • Thread Synchronization
  • Exception Handling
  • Java JDBC Driver
  • Java Database Connectivity steps
  • Lambda Expressions
  • Concurrent Collections
  • National Farmers Day in Hindi | राष्ट्रीय किसान दिवस पर निबंध | चौधरी चरण सिंह जयंती
  • Human rights day in Hindi: 10 दिसंबर ह्यूमन राइट्स डे
  • Unicef day is celebrated on December 11 | Speech on unicef day
  • Indian Navy Day: जल सेना दिवस कब और क्यों मनाया जाता है?
  • P V Sindhu Biography in Hindi, Badminton, State, Caste पी. वी. सिंधु जीवन परिचय, कहानी, राज्य, जाति
  • Draupadi Murmu Biography In Hindi | द्रौपदी मुर्मू की जीवनी
  • Difference between TCP and UDP
    Difference between TCP and UDP | TCP vs UDP examples Differences
  • Difference between Internet and Intranet
    Difference between Internet and Intranet Differences
  • OSI Model | 7 Layers of OSI Model in Computer network
    OSI Model | 7 Layers of OSI Model in Computer network, Functions Networking
  • Network kya hai (नेटवर्क क्या है)
    Network kya hai (नेटवर्क क्या है) Networking
  • IPv4 Vs IPv6 | Difference between IPv4 and IPv6
    IPv4 Vs IPv6 | Difference between IPv4 and IPv6 Differences
  • Similarities and difference between OSI and TCP/IP model
    OSI vs TCP/IP Model, Similarities and difference between OSI and TCP/IP model Networking
  • TCP/IP Model, Full Form, Layers and their Functions
    TCP/IP Model, Full Form, Layers and their Functions Networking
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved