Difference Between Lock and Monitor in Java Concurrency


In Java, concurrency is a technique that allows multiple tasks or processes to run simultaneously on a single processor or multiple processors. It can improve the performance and responsiveness of applications. However, it also introduces new challenges and complexities to the Java developers, such as synchronization and deadlock. To handle these complexities, Java provides a lock and monitor. Both are correlated to each other and used to synchronize access to shared resources and ensure thread safety. But, there exist some differences between a lock and a monitor in terms of their functionality and usage.

Lock vs Monitor

Monitor

When we work in a multi-threading environment, where multiple threads access shared resources then, we need some way to ensure that only one thread accesses a resource at a time. Because if we fail to establish cooperation between these threads, it might create a faulty outcome of the allocated task. Synchronization is the way to achieve this.

The core of the synchronization is the monitor which is an object that establishes mutually exclusive lock. The monitor is like a synchronized region that can be acquired by only one thread at a specific time.

Lock

When multiple threads try to access a shared resource then, the Lock object restricts access to a single thread at a time through ‘lock()’ and ‘unlock()’ methods. Threads request to acquire the Lock object through ‘tryLock()’ method. When lock gets assigned to it and it releases the lock after the completion of task. Till the resources are busy other threads wait in a queue for their turn.

The lock allows a thread to work independently on shared resources without the interference of the other threads. Also, a single thread can ask for the lock multiple times.

Approach

  • Create a class named ‘Thrd’ and inside it define a static synchronized method named ‘operation()’ along with an argument.

  • Now, in this method, take a for loop that will run 4 times and perform the sum operation. The try block of this loop will print the output with a specified time interval i.e. 1000 milliseconds.

  • Moving further, create three Threads. Inside these threads pass the arguments to the ‘operation()’ method.

  • At last, in the main method create three objects for the thread class and execute them using the inbuilt method ‘start()’.

Example of Synchronization

The following example demonstrates what we have discussed till this point.

class Thrd {
   public static synchronized void operation(int data) {
      for(int i = 1; i <= 4; i++) {
         int sum = i + data;
         System.out.println(sum);
         try {
            // each iteration performed with interval of 1 sec
            Thread.sleep(1000);
         } catch(Exception exp){}
      }
   }
}
class Thrd1 extends Thread { // thread number 1
   public void run() {
      Thrd.operation(1);
   }
}
class Thrd2 extends Thread { // thread number 2
   public void run() {
      Thrd.operation(5);
   }
}
class Thrd3 extends Thread { // thread number 3
   public void run() {
      Thrd.operation(10);
   }
}
public class ThrdExecution {
   public static void main(String args[]) {
      // creating object for thread class
      Thrd1 oprt1 = new Thrd1();
      Thrd2 oprt2 = new Thrd2();
      Thrd3 oprt3 = new Thrd3();
      // Starting the thread operation
      oprt1.start();
      oprt2.start();
      oprt3.start();
   }
}

Output

2
3
4
5
11
12
13
14
6
7
8
9

Difference between Lock and Monitor

Lock

Monitor

It provides explicit control over synchronization means it allows the programmer to explicitly acquire and release them.

It provides implicit control over synchronization. It is automatically managed by a run time environment.

It is comparatively less used than monitor.

It is widely used

It is a little complex to implement but more flexible than monitor.

It is simpler to implement and provides less flexibility compared to lock.

A lock can be acquired and released by thread multiple times.

A thread can use only one monitor for each resource.

Lock allows a thread to check if it can acquire the lock by calling its tryLock()method.

The same case is not possible with the Monitor.

Conclusion

In this article, we have discussed one of the most important topics of synchronization that pushes the threads to execute blocks of code sequentially. The Lock and Monitor are the base of synchronization. Logically speaking, there is no difference between them, they actually complement each other. When a thread acquires a lock, it enters the monitor, which is a synchronized region.

Updated on: 21-Jul-2023

328 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements