The Wayback Machine - https://web.archive.org/web/20240917132118/https://www.geeksforgeeks.org/difference-between-lock-and-monitor-in-java-concurrency/
Open In App

Difference Between Lock and Monitor in Java Concurrency

Last Updated : 06 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 classes
import java.io.*;
 
// Class 1
// Helper class
class 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 block for 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 class
class 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 class
class Thread2 extends Thread {
 
    SharedDataPrinter p;
 
    public Thread2(SharedDataPrinter p) { this.p = p; }
 
    public void run()
    {
 
        // Print statement
        p.display(" for Geeks");
    }
}
 
// Class 3
// Main class
class 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

Have been used since the coining of Multithreading concepts. Came into existence with later developments in the field.
Usually in the form of a data field or flag that helps implement coordination.  Synchronicity is implemented via a construct mechanism.A similar
Critical Section (the lock/unlock functions and other operations on the shared object) is a part of the thread itself.  Similar mechanism of lock/unlock for synchronization along with operational functions (such as read/write) is present with the shared object only.
Implementation of mutual exclusion (execution of one thread preventing others’ execution) and cooperation (threads working on a common task) is the responsibility of the threads.  Mutual Exclusion between different set of threads and cooperation (if needed) is all handled by the shared resource itself.
Loosely linked mechanism as all the threads are independent and handle their synchronization in access control themselves. The mechanism is quite robust and reliable as everything is managed at the resource side only.
This method is highly prone to errors when locking time and the constructed mechanism use thread synchronization operation time slice are comparable. There is a good chance that while a thread puts a lock its time slice gets over and the other thread starts working on the resource. The monitors are well designed to work with small thread pools and perform very efficiently unless inter thread communication becomes a necessity.
Ready queue or thread pools are either not present or else handled by the operating system. Threads wait in queues managed by the shared object they all are trying to access control over.
Locks independently are not much in use and are implemented much less widely.  Monitors intrinsically use inter-thread locks only and are much more in usage. 

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

 



Previous Article
Next Article

Similar Reads

What is Lock Striping in Java Concurrency?
Lock striping is where the locking happens on a few containers or stripes or buckets, implying that getting to a pail just bolts that can and not the whole information structure. That is the idea of lock striping. Having separate locks for a bit of an information structure where each lock is locking on a variable measured arrangement of autonomous
2 min read
Object Level Lock vs Class Level Lock in Java
Synchronized is the modifier applicable only for methods and blocks but not for classes and variables. If multiple threads are trying to operate simultaneously on the same java object then there may be a chance of data inconsistency problem to overcome this problem we should go for a 'synchronized' keyword. If a method or block declares as synchron
6 min read
Java Concurrency - yield(), sleep() and join() Methods
In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three. We can prevent the execution of a thread by using one of the following methods of the Thread class. All three
5 min read
Structured Concurrency in Java
Structured concurrency organizes concurrent processes in a controlled way to ease concurrent execution. It prevents race situations, deadlocks, and orphaned jobs. Structured concurrency may be implemented in Java utilizing libraries, frameworks, or experimental initiatives like Project Loom. Structured concurrency concepts and techniques in Java: E
2 min read
Lock framework vs Thread synchronization in Java
Thread synchronization mechanism can be achieved using Lock framework, which is present in java.util.concurrent package. Lock framework works like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. Locks allow more flexible structuring of synchronized code. This new approach was introduced in Java 5 to tackl
5 min read
AtomicInteger for Lock Free Algorithms in Java
Lock-Free Algorithms is one of the mechanisms in which thread-safe access to shared data is possible without the use of Synchronization primitives like mutexes. Multi-threaded applications have shared resources that may be passed among different threads used in the application. This poses the threat of race conditions and data races among the threa
5 min read
Lock Free Stack using Java
In a multi-threaded environment, the lock-free algorithms provide a way in which threads can access the shared resources without the complexity of Locks and without blocking the threads forever. These algorithms become a programmer’s choice as they provide higher throughput and prevent deadlocks. This is mainly because designing lock-based algorith
8 min read
Class Level Lock in Java
Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock. Class level lock prevents multiple threads to enter a synchronized block in any of all available instances of the class on runtime. This means if in runtime there are 10
5 min read
Reentrant Lock in Java
Background The traditional way to achieve thread synchronization in Java is by the use of synchronized keyword. While it provides a certain basic synchronization, the synchronized keyword is quite rigid in its use. For example, a thread can take a lock only once. Synchronized blocks don't offer any mechanism of a waiting queue and after the exit of
9 min read
Object Level Lock in Java
Every object in Java has a unique lock. Whenever we are using a synchronized keyword, then only the lock concept will come into the picture. An object-level lock is a mechanism when we want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on a given instance of the class. I
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Difference between a Java Application and a Java Applet
Java Application is just like a Java program that runs on an underlying operating system with the support of a virtual machine. It is also known as an application program. The graphical user interface is not necessary to execute the java applications, it can be run with or without it. Java Applet is a Java program that can be embedded into a web pa
3 min read
Difference between Java IO and Java NIO
Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API's. In this article, the difference between these two IO pack
3 min read
Difference between Java and Core Java
Java is a very famous language that is based on the object-oriented programming concepts. It is the successor of the C and C++ languages. It was developed by Sun Microsystems. Core Java is a term used by Sun Microsystems to refer to the Java to standard edition J2SE. This is the parent of all other editions of Java used on internet sites. It has a
2 min read
Difference Between java.lang and java.util
Java Packages contain classes, interfaces, and sub-packages. The packages java.lang and java.util are two of the most commonly used packages in Java Standard Library. Both packages contain useful classes and utilities. In this article, we will learn about java.lang and java.util package with examples and also the difference between these two packag
2 min read
Difference between Core Java and Advanced Java
Java is a versatile and widely used programming language that helps in the development of many software applications. It is popular for its portability, robustness, and ease of use, making it a preferred choice for both beginners and experienced developers. Java's ecosystem can be largely categorized into two main parts that are Core Java and Advan
4 min read
Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
6 min read
Similarities and Difference between Java and C++
Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynamic memory utilization. Java is widely used in the
6 min read
Difference Between Length and Capacity in Java
Length and capacity are two different things in Java. Length basically increases when characters are appended to the string whereas the capacity increases when the current capacity is exceeded by a new length. length () method is a part of the Java String class. It is used to find the length of the string. It basically counts the number of characte
3 min read
Difference Between throw and throws in Java
Prerequisite: Throw and Throws in Java The throw and throws are the concepts of exception handling in Java where the throw keyword throws the exception explicitly from a method or a block of code, whereas the throws keyword is used in the signature of the method. The differences between throw and throws in Java are: S. No. Key Difference throw thro
2 min read
Difference between Traditional Collections and Concurrent Collections in java
We all know about Traditional Collections ( i.e. List, Set, Queue and its implemented Classes) and Concurrent Collection (i.e. ConcurrentMap interface, ConcurrentHashMap class, CopyOnWriteArrayList class etc). In these two Collections, there are few differences like: Most of the Classes which are present in Traditional Collections (i.e ArrayList, L
3 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Difference Between LinkedList and LinkedHashSet in Java
In this article you will learn difference between LinkedList and LinkedHashSet in java. Prerequisite: LinkedList : LinkedHashSet LinkedList class implements the List and Deque interface and extends from AbstractSequentialList class. LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. Java Linked
3 min read
Difference between length of Array and size of ArrayList in Java
Array has length property which provides the length of the Array or Array object. It is the total space allocated in memory during the initialization of the array. Array is static so when we create an array of size n then n blocks are created of array type and JVM initializes every block by default value. Let's see this in the following figure. On
2 min read
Difference between ArrayList and HashSet in Java
Here are couple of differences between ArrayList and HashSet. Inheritance: Implementation: Implementation : ArrayList implements List interface while HashSet implements Set interface in Java.Internal implementation: ArrayList is backed by an Array while HashSet is backed by an HashMap.Duplicates : ArrayList allows duplicate values while HashSet doe
3 min read
What is the difference between field, variable, attribute, and property in Java
Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some p
2 min read
Difference Between Daemon Threads and User Threads In Java
In Java, there are two types of threads: Daemon ThreadUser Thread Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks. Differ
4 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Difference Between ArrayList and HashMap in Java
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java's collection since Java 1.2. It provides the basic implementation o
7 min read
Difference between Java and C language
Here are some of the differences between Java and C language. C is much faster than Java Java is slower than C due to overhead. C Java C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.C is a Procedural Programming Language.Java is Object-Oriented language.C is more procedure-oriented.Java is mor
3 min read
Article Tags :
Practice Tags :