Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Lock framework
2.1.
Example
3.
Thread Synchronization 
3.1.
Example 
4.
Lock framework vs. Thread synchronization
5.
Frequently Asked Questions
6.
Conclusion
Last Updated: Mar 27, 2024

Lock frameworks vs. thread synchronization

Author Shivam Verma
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Before knowing about the difference between lock frameworks and thread synchronization, we have to know about these things.

Lock framework works like synchronized blocks in Java. It is available in Java.util.concurrent package.

Thread synchronization means that every access to data shared between threads is protected so that when any thread starts operation on the shared data, no other thread is allowed access until the first thread is done.

You can also read about the Multiple Inheritance in Java.

Lock framework

The lock framework works like synchronized blocks in Java, except locks can be more sophisticated than synchronized blocks of Java. The lock framework is available in the Java.util.concurrent package. Java locks act as a thread synchronization mechanism similar to synchronized blocks. This mechanism was introduced in Java 5 and provided more options than the Synchronized block. 

Read More About, Basics of Java

Example

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class DisplayDemo
{
    private final Lock QueueLock = new ReentrantLock();
    public void display()
    {
        QueueLock.lock();
        try
        {
            Long time=(long) (Math.random()*4000);
            System.out.println(Thread.currentThread().getName()+" Time stack "+(time/1000)+" seconds.");
            Thread.sleep(time);
        }
        catch(InterruptedException exp)
        {
            exp.printStackTrace();
        }
        finally
        {
            System.out.printf("%s displayed the document successfully.\n", Thread.currentThread().getName());
            QueueLock.unlock();
        }
    }
}
class ThreadDemo extends Thread
{
    DisplayDemo displayDemo;
    ThreadDemo(String str_name,  DisplayDemo displayDemo)
    {
        super(str_name);
        this.displayDemo=displayDemo;
    }
    @Override
    public void run()
    {
        System.out.printf("%s starts displaying a document\n", Thread.currentThread().getName());
        displayDemo.display();
   }
}
public class Example_Lock
{
public static void main (String[] args) throws java.lang.Exception
{
    DisplayDemo DD= new DisplayDemo();
    ThreadDemo th1 = new ThreadDemo("Thread-1 ", DD);
        ThreadDemo th2 = new ThreadDemo("Thread-2 ", DD);
        ThreadDemo th3 = new ThreadDemo("Thread-3 ", DD);
        ThreadDemo th4 = new ThreadDemo("Thread-4 ", DD);
        th1.start();
        th2.start();
        th3.start();
        th4.start();
}
}

Output

Thread-1  starts displaying a document
Thread-1  Time stack 3 seconds.
Thread-2  starts displaying a document
Thread-3  starts displaying a document
Thread-4  starts displaying a document
Thread-1  displayed the document successfully.
Thread-2  Time stack 1 seconds.
Thread-2  displayed the document successfully.
Thread-3  Time stack 3 seconds.
Thread-3  displayed the document successfully.
Thread-4  Time stack 1 seconds.
Thread-4  displayed the document successfully.

The above program demonstrates some methods of the Lock interface. Here we have used lock() to acquire the lock and unlock() to release the lock. We have used ReentrantLock class as an implementation of the Lock interface.

Try it on java online compiler.

Must Read Static Blocks In Java.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Thread Synchronization 

In Java, synchronization is the capability to control the access of multiple threads to any shared resource. The mechanism of allowing only one thread to use the object when multiple threads are trying to use the particular object simultaneously is called thread Synchronization. We can achieve the thread synchronization mechanism by using the Lock framework, which is present in java.util.concurrent package.

Example 

import java.util.*;
import java.lang.*;
import java.io.*;
class ThreadDemo implements Runnable
{
    int token=1;
    public void run ()
    {
        synchronized (this)
        {
            Thread th=Thread.currentThread();
            String str_name=th.getName();
            System.out.println(token+"...allocated  to "+str_name);
            token++;
        }
    }
}
public class Example_ThreadSynchronisation
{
public static void main (String[] args) throws java.lang.Exception
{
ThreadDemo td=new ThreadDemo();
        Thread th1=new Thread(td);
        Thread th2=new Thread(td);
        Thread th3=new Thread(td);
        th1.setName ("Thread1");
        th2.setName ("Thread2");
        th3.setName ("Thread3");
        th1.start();
        th2.start();
        th3.start();
}
}

Output

1...allocated  to Thread1
2...allocated  to Thread2
3...allocated  to Thread3

Here in the above example, we have achieved thread Synchronization with the help of Synchronized Block in Java.

Also Read About, Multithreading in java

Lock framework vs. Thread synchronization

You can also check about Java Tokens here.

Frequently Asked Questions

  1. How many ways can synchronize in Java?
    Ans: Synchronization can be achieved by using the following three ways: 
    By Using the Synchronized Method. 
    By Using Synchronized Block. 
    By Using Static Synchronization.
     
  2. Can a constructor be synchronized in Java?
    Ans: No, a constructor can not be synchronized in Java.
     
  3. What is the advantage of thread Synchronisation?
    Ans: The main advantage of synchronization is that we can resolve the date inconsistency problem by using the synchronized keyword. But the main disadvantage of the synchronized keyword is that it increases the Thread's waiting time and affects the system's performance.

Conclusion

In this article, we have extensively discussed the difference between lock frameworks and thread synchronization in the java programming language. We also discussed the lock frameworks and thread synchronization in Java with the help of an example.

Recommended topic: Interface in Java

We hope that this blog has helped you enhance your knowledge regarding the difference between lock frameworks and thread synchronization. If you want to learn more, check out our article on Java Methods. You can read our Java language articles by clicking Java Archives

Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Reentrant Monitor in Java
Next article
Atomic Variables in Java
Live masterclass