Difference Between Lock and Monitor in Java Concurrency - GeeksforGeeks

24 Feb, 2022
Java Concurrency basically deals with concepts like multithreading and other concurrent operations. This is done to ensure maximum and efficient utilization of CPU performance thereby reducing its idle time in general. Locks have been in existence to implement multithreading much before the monitors have come to usage. Back then locks (or mutex) were parts of threads inside the program that worked on flag mechanisms to synchronize with other threads. They have always been working as a tool to provide synchronous access control over resources and shared objects. With further advancements, the use of monitors started as a mechanism to handle access and coordinate threads which proved to be more efficient, error-free, and compatible in object-oriented programs. Before we move on to find the differences between the two let’s have a closer look into each of them.
Overview of Lock (or Mutex)
Lock originally has been used in the logical section of the threads that were used to provide synchronized access control between the threads. Threads checked the availability of access control over shared objects through flags attached to the object that indicated whether or not the shared resource is free (unlocked) or busy (locked). Now the concurrency API provides support of using locks explicitly using Lock Interface in java. The explicit method has a finer control mechanism as compared to the implicit implementation of locks using monitors. Before we move on to discuss monitors let us look at an illustration that demonstrates the functioning of basic locks.
Monitor – Overview
Monitor in Java Concurrency is a synchronization mechanism that provides the fundamental requirements of multithreading namely mutual exclusion between various threads and cooperation among threads working at common tasks. Monitors basically ‘monitor’ the access control of shared resources and objects among threads. Using this construct only one thread at a time gets access control over the critical section at the resource while other threads are blocked and made to wait until certain conditions. In Java, monitors are implemented using synchronized keyword (synchronized blocks, synchronized methods or classes). For example, let’s see how two threads t1 and t2 are synchronized to use a shared data printer object. 
Java
// Java Program to Illustrate Monitoe in Java Concurrency // Importing input output classesimport java.io.*; // Class 1// Helper classclass SharedDataPrinter {     // Monitor implementation is carried on by    // Using synchronous method     // Method (synchronised)    synchronized public void display(String str)    {         for (int i = 0; i < str.length(); i++) {            System.out.print(str.charAt(i));             // Try-catch bloc kfor exceptions as we are            // using sleep() method            try {                 // Making thread to sleep for very                // nanoseconds as passed in the arguments                Thread.sleep(100);            }            catch (Exception e) {            }        }    }} // Class 2// Helper class extending the Thread classclass Thread1 extends Thread {     SharedDataPrinter p;     // Thread    public Thread1(SharedDataPrinter p)    {         // This keyword refers to current instance itself        this.p = p;    }     // run() method for this thread invoked as    // start() method is called in the main() method    public void run()    {         // Print statement        p.display("Geeks");    }} // Class 2 (similar to class 1)// Helper class extending the Thread classclass Thread2 extends Thread {     SharedDataPrinter p;     public Thread2(SharedDataPrinter p) { this.p = p; }     public void run()    {         // Print statement        p.display(" for Geeks");    }} // Class 3// Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Instance of a shared resource used to print        // strings (single character at a time)        SharedDataPrinter printer = new SharedDataPrinter();         // Thread objects sharing data printer        Thread1 t1 = new Thread1(printer);        Thread2 t2 = new Thread2(printer);         // Calling start methods for both threads        // using the start() method        t1.start();        t2.start();    }}
Output:
Finally wrapping off with the article let us discuss the major differences between Lock and Monitor in concurrency in java that is pictorially depicted in the image below shown as follows: 
Lock (Mutex)
Monitor
Note: 
As we see monitors themselves are implemented with the necessary support of locks, it is often said that they are not different but complementary in the nature of their existence are operating
 
simmytarika5
surinderdawra388
as5853535
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java