Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

What is Lock(), UnLock(), ReentrantLock(), TryLock() and How it’s different from Synchronized Block in Java?]

In this tutorial we will go over Lock(), UnLock(), ReentrantLock(), TryLock() and how it’s different from Synchronized Block in Java.

If you have also below questions then you are at right place.

  • Locks in Java
  • Java Lock Example and Concurrency Lock vs synchronized
  • Java Concurrency Tutorial – Reentrant Locks
  • synchronization – Proper lock/unlock usage for Java
  • java – Synchronization vs Lock
  • java lock unlock example
  • locking mechanism in java
  • java lock unlock different thread

Let’s get started. 1st let’s understand each of these terms and then we will go over working example.

Lock():

java.util.concurrent.locks. A lock is a thread synchronization mechanism like synchronized blocks except locks can be more sophisticated than Java’s synchronized blocks. It is an interfaces and classes providing a framework for locking and waiting for conditions that is distinct from built-in synchronization and monitors.

UnLock():

UnLock() releases the lock on Object.

ReentrantLock():

A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.

TryLock():

TryLock() acquires the lock only if it is free at the time of invocation.

Tip-1

If you’re simply locking an object, I’d prefer to use synchronized.

Lock.lock();
youMethod(); // Throws a NullPointerException!
Lock.unlock(); // Here you never release the lock!

Whereas with synchronized, it’s super clear and impossible to get wrong:

synchronized(myObject) {
      doSomethingNifty();
}

Example Details:

  1. Create class: CrunchifyLockTutorial.java
  2. Create inner classes: Company and CrunchifyLoop
  3. From Main create two objects of class Company
  4. Start thread loop for 10 on those objects
  5. While Company1 talks to Company2 – it locks an object. If at the same time – if Company2 wants to talk to Company1 then it says – Conflicting – Lock already exist. (Both companies are already in talk).
package crunchify.com.tutorial;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Crunchify.com
 *
 */

public class CrunchifyLockTutorial {
        public static void main(String[] args) {
                final Company crunchify = new Company("Crunchify");
                final Company google = new Company("Google");
                new Thread(new CrunchifyLoop(crunchify, google)).start();
                new Thread(new CrunchifyLoop(google, crunchify)).start();
        }

        // Class CrunchifyLoop
        static class CrunchifyLoop implements Runnable {
                private Company companyName1;
                private Company companyName2;

                public CrunchifyLoop(Company companyName1, Company companyName2) {
                        this.companyName1 = companyName1;
                        this.companyName2 = companyName2;
                }

                public void run() {
                        Random random = new Random();
                        // Loop 10
                        for (int counter = 0; counter <= 10; counter++) {
                                try {
                                        Thread.sleep(random.nextInt(5));
                                } catch (InterruptedException e) {
                                }
                                companyName2.crunchifyTalking(companyName1);
                        }
                }
        }

        // Class Company
        static class Company {
                private final String companyName;

                // ReentrantLock: Creates an instance of ReentrantLock. This is equivalent to using ReentrantLock(false)
                private final Lock lock = new ReentrantLock();

                // Constructor
                public Company(String name) {
                        this.companyName = name;
                }

                public String getName() {
                        return this.companyName;
                }

                public boolean isTalking(Company companyName) {
                        Boolean crunchifyLock = false;
                        Boolean googleLock = false;
                        try {
                                // tryLock: Acquires the lock only if it is free at the time of invocation.
                                crunchifyLock = lock.tryLock();
                                googleLock = companyName.lock.tryLock();
                        } finally {
                                if (!(crunchifyLock && googleLock)) {
                                        if (crunchifyLock) {
                                                // unlock: Releases the lock.
                                                lock.unlock();
                                        }
                                        if (googleLock) {
                                                companyName.lock.unlock();
                                        }
                                }
                        }
                        return crunchifyLock && googleLock;
                }

                public void crunchifyTalking(Company companyName) {
                        // Check if Lock is already exist?
                        if (isTalking(companyName)) {
                                try {
                                        System.out.format("I'm %s: talking to %s %n", this.companyName, companyName.getName());
                                } finally {
                                        lock.unlock();
                                        companyName.lock.unlock();
                                }
                        } else {
                                System.out.format("\tLock Situation ==> I'm %s: talking to %s, but it seems"
                                                + " we are already talking. Conflicting. %n", this.companyName, companyName.getName());
                        }
                }
        }
}

Output:

I'm Crunchify: talking to Google 
        Lock Situation ==> I'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. 
I'm Google: talking to Crunchify 
I'm Google: talking to Crunchify 
I'm Crunchify: talking to Google 
I'm Google: talking to Crunchify 
I'm Google: talking to Crunchify 
I'm Crunchify: talking to Google 
        Lock Situation ==> I'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. 
        Lock Situation ==> I'm Crunchify: talking to Google, but it seems we are already talking. Conflicting. 
        Lock Situation ==> I'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. 
I'm Crunchify: talking to Google 
I'm Google: talking to Crunchify 
I'm Google: talking to Crunchify 
I'm Crunchify: talking to Google 
I'm Google: talking to Crunchify 
        Lock Situation ==> I'm Google: talking to Crunchify, but it seems we are already talking. Conflicting. 
        Lock Situation ==> I'm Crunchify: talking to Google, but it seems we are already talking. Conflicting. 
I'm Crunchify: talking to Google 
I'm Crunchify: talking to Google 
I'm Crunchify: talking to Google 
I'm Crunchify: talking to Google

Tip-2

You can achieve everything the utilities in java.util.concurrent do with the low-level primitives like synchronized, volatile, or wait.

The post What is Lock(), UnLock(), ReentrantLock(), TryLock() and How it’s different from Synchronized Block in Java?] appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires