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");
              }else{
                fromAccount.debit(amount);
                toAccount.credit(amount);
              }
            }finally{
              toAccount.lock.unlock();
            }
          }
        }finally{
          fromAccount.lock.unlock();
        }
      }
      if(System.nanoTime() < stopTime)
        return false;
      Thread.sleep(100);
    }//end of while
</pre>

References: http://www.fanyeong.com/2015/10/09/%E5%8F%AF%E9%87%8D%E5%85%A5%E6%80%A7%E5%8F%8A%E5%85%B6%E4%BB%96/

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 WordPress.com
Get started
%d bloggers like this: