Thursday, June 13, 2024
HomeJavaDistinction between ReentrantLock vs synchronized lock in Java? Instance Tutorial

Distinction between ReentrantLock vs synchronized lock in Java? Instance Tutorial


5. As a result of above distinction, working with synchronized lock is much less error inclined than working with ReentrantLock. Since lock is launch mechanically even in case of exception, it is even protected for freshmen to write down code utilizing synchronized block, however you want some extra care whereas utilizing lock interface and ReentrantLock.  You should comply with the usual idiom proven above and should keep in mind to launch lock in lastly block, in order that lock is launch beneath all circumstances.

Now, Let’s examine an instance for instance the distinction between ReentrantLock and the synchronized lock in Java.

Instance Situation: Financial institution Account Stability Replace

Think about a easy state of affairs the place a number of threads try and replace a shared checking account stability concurrently. To take care of knowledge integrity, we have to be certain that just one thread can replace the stability at a time.

Utilizing synchronized Block:

public class BankAccount {
    personal double stability;
    personal closing Object lock = new Object();

    public void deposit(double quantity) {
        synchronized (lock) {
            stability += quantity;
        }
    }

    public void withdraw(double quantity) {
        synchronized (lock) {
            stability -= quantity;
        }
    }
}

On this instance, we use the synchronized key phrase with a lock object (lock) to realize mutual exclusion. The lock ensures that just one thread can execute the deposit or withdraw strategies at any given time, stopping potential knowledge race points.

Utilizing ReentrantLock:

import java.util.concurrent.locks.*;

public class BankAccount {
    personal double stability;
    personal closing ReentrantLock lock = new ReentrantLock();

    public void deposit(double quantity) {
        lock.lock();
        attempt {
            stability += quantity;
        } lastly {
            lock.unlock();
        }
    }

    public void withdraw(double quantity) {
        lock.lock();
        attempt {
            stability -= quantity;
        } lastly {
            lock.unlock();
        }
    }
}

On this model, I’ve used ReentrantLock to realize the identical synchronization as earlier than. The lock object is acquired utilizing lock.lock(), and the essential part is protected utilizing a try-finally block to make sure the lock is launched even when an exception happens.

Key Variations:

Now, that we now have seen the instance and in addition know the distinction between ReentrantLock and sycnhronzied lock, let’s discover these variations on this instance:

1. Flexibility

ReentrantLock affords extra flexibility in comparison with the synchronized block. For instance, it means that you can attempt to purchase the lock with a timeout (tryLock()) or try to amass the lock interruptibly (lockInterruptibly()), which may be helpful in sure conditions.

2. Readability

The synchronized block makes use of the acquainted synchronized key phrase, which may make the code extra readable. ReentrantLock code could also be a bit extra verbose as a consequence of express lock acquisition and launch.

3. Efficiency

In some instances, ReentrantLock can present higher efficiency than synchronized as a consequence of its improved dealing with of competition. Nevertheless, the precise efficiency acquire varies relying on the use case and JVM implementation.

4. Nested Locking

ReentrantLock helps nested locking, which suggests a thread can purchase the identical lock a number of instances (so long as it releases it an equal variety of instances). This isn’t attainable with synchronized, because it mechanically re-entrant.

In conclusion, each ReentrantLock and synchronized can be utilized to realize synchronization in Java. ReentrantLock affords extra superior options and adaptability, however it may include further complexity. Then again, synchronized is easy and simpler to make use of however lacks among the options provided by ReentrantLock. Your alternative between the 2 needs to be based mostly in your particular necessities and efficiency concerns.

Associated Java Concurrency Articles you might like

  • 5 Programs to Study Java Multithreading in-depth (programs)
  • Distinction between CyclicBarrier and CountDownLatch in Java? (reply)
  • How does Exchanger works in Java Multithreading (tutorial)
  • 21 Tech Abilities Java Developer can study (abilities)
  • Distinction between Thread and Executor in Java? (reply)
  • 10 Tricks to change into a greater Java Developer (ideas)
  • 10 Greatest programs to study Java in depth (programs)
  • Understanding the circulate of information and code in Java program (reply)
  • The way to keep away from impasse in Java? (reply)
  • The way to do inter-thread communication in Java utilizing wait-notify? (reply)
  • 5 Important Abilities to Crack Java Interviews (abilities)
  • High 5 Books to Grasp Concurrency in Java (books)
  • High 50 Multithreading and Concurrency Questions in Java (questions)
  • 10 Superior Java Programs for Skilled Devs (programs)

Thanks for studying this text to date. For those who discover this text helpful then please share with your mates and colleagues. You probably have any questions or suggestions then please drop a be aware.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments