Object Level Locking In Java

Posted By : Aftab Alam | 28-Sep-2019

1. Introduction:- As a Java developer, everybody knows that Java is a programming language which provides multi-threading at programming(application) level means provides concurrency. Concurrency means more than one thread can operate on the same data at a time but when two threads are being operated on the same data it leads to data inconsistency problem. For providing solution(s) to these problems, locking came into the picture.

2. Requirements:- To executed this program, pre-requisites have been listed below out.
    2.1. Ubuntu 14.04 LTS
    2.2. Ubuntu gedit editor
    2.3. java version "1.8.0_181" 

3. Types of Locking:- Java programming provides two types of locking which are object and class level locking. This blog will be revolving around object-level locking.

  3.1. Object Level Locking:- Object-level locking refers to that when one thread is acquiring an object another thread should not access a critical section of currently running thread. For achieving locking, synchronization came into the picture. It is specific to instance-level properties/methods in an object.

  3.2. Class Level Locking:- 

4. Synchronization:- Synchronisation is a process which doesn't allow another thread to enter in a critical section of the first thread. In other words, it doesn't allow another thread to be operated on the same data until the first thread is finished. There are two ways of achieving object locking in java.
   4.1. Syncronised Method:- Java Programming provides a "synchronized" keyword in java. When it is used with method it leads to the implementation of the synchronised method. When it's used with block then it leads to synchronized block.
   4.2. Syncronised Block:- When we want a few lines of code is sensitive which can not be accessed by multiple threads at a time then we go for the synchronised block. It increases the performance of the program as compared to the synchronised method.

5. Implementation:- In this section, implementation for multi-threading without synchronization, with the synchronization method and synchronization block have been explained with programming example.
  5.1. Non-synchronisation implementation:- It has been implemented by creating three classes Display, MyThread, and ThreadDemo.
    5.1.1. A class, named as Display, which consists of a non-syncronised, named as wish, method on which multiple threads wants to operate. Multiple threads can operate on the method concurrently.

  public class Display {
     public void wish(String name) {
        for(int i=0; i<10; i++) {
	   System.out.print("Good Morning: ");
	   try {
	      Thread.sleep(2000);
	   } 
	   catch(InterruptedException IE){
	      IE.printStackTrace();
	   }
	   System.out.println(name);
        }
     }
   }

5.1.2. Now we need a class to create multiple threads. So a class, named as MyThread, is created which implements Thread class and overrides its run method as per the requirement. It also has a parameterised consructor.    

   public class MyThread extends Thread {
      Display display;
      String name;    
    
      public MyThread(Display display, String name) {
         this.display=display;
         this.name=name;
      }
    
      public void run() {
       display.wish(name);
     }
   }

5.1.3. In below demo class, named as ThreadDemo, an instance of Display class and two instances of MyThread classes are created. Both threads want to operate on the same object so the output will be random which may lead to data inconsistency.   

  public class ThreadDemo {

    public static void main(String a[]) {
       Display display = new Display();
       MyThread myThread1 = new 
       MyThread(display, "Sultan Husain");
       MyThread myThread2 = new 
       MyThread(display, "Aftab Alam");
       myThread1.start();
       myThread2.start();
    }
  }

 5.1.4. Commands:- To compile and execute this program, listed below commands are used on ubuntu terminal.
   5.1.4.1. "javac ThreadDemo.java" to compile the java program
   5.1.4.2. "java ThreadDemo" to execute the program which produces the result shown in below screenshot.
 5.1.5. Output:- When the above program is executed then It produces an output which is shown in the screenshot.

5.2. Synchronized method implementation:- In-display class, if only wish method is made synchronized by using a synchronised keyword before wish method then it would be implemented for object locking by a synchronised method.

public class Display {

    public synchronized void wish(String name) {
       for(int i=0; i<10; i++) {
          System.out.print("Good Morning: ");
          try {
            Thread.sleep(2000);
          } 
          catch(InterruptedException IE) {
            IE.printStackTrace();
          }
          System.out.println(name);
       }
     }
   } 

    Output:- When the above program is executed then It produces an output which is shown in the screenshot.

5.3. Synchronized block implementation:- In-display class, instead of using synchronised keyword before method, a synchronised block is created on the current object.  

  public class Display {

     public void wish(String name) {
        synchronized(this) {
          for(int i=0;i<10;i++){
             System.out.print("Good Morning: ");
             try {
               Thread.sleep(2000);
             } 
             catch(InterruptedException IE){
               IE.printStackTrace();
             }
             System.out.println(name);
          }
       }
     }
  }

    Output:- When the above program is executed then It produces an output which is shown in the screenshot.

6. Advantages:- It offers many advantages as listed below.
   6.1. It is very beneficial while implementing finance related system(s) because one thread is running on some data another thread will not be executed on the same until the first one is executed completely.
   6.2. It is thread-safe.

7. Disadvantages:- It has some disadvantages as well.
   7.1. It decreases the performance of the system as only one thread is allowed to be operated at a time.

8. Conclusion:- As every system has its specification and need, so multi-threading is beneficial or not it mostly depends on the need of the system but most of the system using multi-threading with some precaution as listed above some of them.

About Author

Author Image
Aftab Alam

Aftab has worked on multiple technologies in front-end as well as in back-end.

Request for Proposal

Name is required

Comment is required

Sending message..