Why Synchronization is Required?

  1. Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out.
  2. Data integrity
  3. To work with a common shared resource which is very essential in the real world such as in banking systems.

Note: Do not go for synchronized keyword unless it is most needed, remember this as there is no priority setup for threads, so if the main thread runs before or after other thread the output of the program would be different.

The biggest advantage of synchronization is the increase in idiotic resistance as one can not choose arbitrarily an object to lock on as a result string literal can not be locked or be the content. Hence, these bad practices are not possible to perform on synchronized method block.

As we have seen humongous advantages and get to know how important it is but there comes disadvantage with it.

Disadvantage: Performance issues will arise as during the execution of one thread all the other threads are put to a blocking state and do note they are not in waiting state. This causes a performance drop if the time taken for one thread is too long.
 

multi-tasking

As perceived from the image in which we are getting that count variable being shared resource is updating randomly. It is because of multithreading for which this concept becomes a necessity.
 

  • Case 1: If ‘main thread’ executes first then count will be incremented followed by a ‘thread T’ in synchronization
  • Case 2: If ‘thread T‘ executes first then count will not increment followed by ‘main thread‘ in synchronization

Implementation: Let us take a sample program to observe this 0 1 count conflict
 

Example:
 

Java
// Java Program to illustrate Output Conflict between
// Execution of Main thread vs Thread created

// count = 1 if main thread executes first
// count = 1 if created thread executes first

// Importing basic required libraries
import java.io.*;
import java.util.*;

// Class 1
// Helper Class extending Thread class
class MyThread extends Thread {

    // Declaring and initializing initial count to zero
    int count = 0;

    // Method 1
    // To increment the count above by unity
    void increment() { count++; }

    // Method 2
    // run method for thread invoked after
    // created thread has started
    public void run()
    {

        // Call method in this method
        increment();

        // Print and display the count
        System.out.println("Count : " + count);
    }
}

// Class 2
public class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating the above our Thread class object
        // in the main() method
        MyThread t1 = new MyThread();

        // start() method to start execution of created
        // thread that will look for run() method
        t1.start();
    }
}

Output:

Output Explanation:

Here the count is incremented to 1 meaning ‘main thread‘ has executed prior to ‘created thread‘. We have run it many times and compiled and run once again wherein all cases here main thread is executing faster than created thread but do remember output may vary. Our created thread can execute prior to ‘main thread‘ leading to ‘Count : 0’ as an output on the console. 
 

Now another topic that arises in dealing with synchronization in threads is Thread safety in java synchronization is the new concept that arises out in synchronization so let us discuss it considering

  • A real-life scenario followed by
  • Pictorial representation as an illustration followed by
  • Technically description and implementation

Java Multithreading Tutorial

Threads are the backbone of multithreading. We are living in a real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking efficiently. It is achieved by the concept of thread. 

Similar Reads

Real-life Example of Java Multithreading

Suppose you are using two tasks at a time on the computer, be it using Microsoft Word and listening to music. These two tasks are called processes. So you start typing in Word and at the same time start music app, this is called multitasking. Now you committed a mistake in a Word and spell check shows exception, this means Word is a process that is broken down into sub-processes. Now if a machine is dual-core then one process or task is been handled by one core and music is been handled by another core....

Two Ways to Implement Multithreading

Using Thread ClassUsing Runnable Interface...

Method 1: Using Thread Class

Java provides Thread class to achieve programming invoking threads thereby some major methods of thread class are shown below in the tabular format with which we deal frequently along the action performed by them....

Synchronization

It is the mechanism that bounds the access of multiple threads to share a common resource hence is suggested to be useful where only one thread at a time is granted the access to run over....

Why Synchronization is Required?

Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out.Data integrityTo work with a common shared resource which is very essential in the real world such as in banking systems....

Real-life Scenario

Suppose a person is withdrawing some amount of money from the bank and at the same time the ATM card registered with the same account number is carrying on withdrawal operation by some other user. Now suppose if withdrawing some amount of money from net banking makes funds in account lesser than the amount which needed to be withdrawal or the other way. This makes the bank unsafe as more funds are debited from the account than was actually present in the account making the bank very unsafe and is not seen in daily life. So what banks do is that they only let one transaction at a time. Once it is over then another is permitted....

Conclusion

Understanding Java Multithreading is important for creating fast and efficient applications. By using multithreading, you can run multiple tasks at the same time, making your programs more responsive and powerful. Key ideas like thread synchronization, concurrent collections, and the executor framework help manage multiple threads safely. In the above article we have described all details about Java multithreading....

Java Multithreading Tutorial – FAQs

What is multithreading in Java?...

Contact Us