ReentrantLock VS Synchronized

ReetrantLock is supported in and java 5.0, cause key word–synchronized has some defects:

  1. not interruptible for synchronized
  2. wait for lock without timeout
  3. cannot be used in non-block statement

Then reentrantLock solve some above issues:

  1. support non-block structure.
  2. support fairness lock. fair lock principle is passing lock to the longest waiting thread; Unfair lock will not grantee the sequence for thread to get lock. Fairness lock’s performance is limited as a waiting state of thread should be notify to active and new active thread need to be changed to waiting.
  3. release the lock when get interruption signal.
  4. support timed out lock, tryLock(). This method will break the fairness lock setting, even this reentrantLock has a true fair setting. In order not break the fairness, we could use tryLock(0,TimeUtil.SECONDS), it means that got lock return true, rather than return false, additionally, it will wait for given time to acquire lock .
<pre class="wp-block-syntaxhighlighter-code">
   public boolean transferMoneyWithTryLock(Account fromAccount, Account toAccount, float amount) throws InsufficientAmountException, InterruptedException {
    // we are defining a stopTime
    long stopTime = System.nanoTime() + 5000;
    while (true) {
      if (fromAccount.lock.tryLock()) {
        try {
          if (toAccount.lock.tryLock()) {
            try {
              if (amount > fromAccount.getCurrentAmount()) {
                throw new InsufficientAmountException(
                        "Insufficient Balance");
      if(System.nanoTime() < stopTime)
        return false;
    }//end of while


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at
Get started
%d bloggers like this: