• Java Lock Example – ReentrantLock(java锁的例子)


    Welcome to Java Lock example tutorial. Usually when working with multi-threaded environment, we use synchronized for thread safety.

    Java Lock

    java lock, java lock example, ReentrantLock in Java, java locks

    Most of the times, synchronized keyword is the way to go but it has some shortcomings that lead the way to inclusion of Lock API in Java Concurrency package. Java 1.5 Concurrency API came up with java.util.concurrent.locks package with Lock interface and some implementation classes to improve the Object locking mechanism.

    Some important interfaces and classes in Java Lock API are:

    1. Lock: This is the base interface for Lock API. It provides all the features of synchronized keyword with additional ways to create different Conditions for locking, providing timeout for thread to wait for lock. Some of the important methods are lock() to acquire the lock, unlock() to release the lock, tryLock() to wait for lock for a certain period of time, newCondition() to create the Condition etc.
    2. Condition: Condition objects are similar to Object wait-notify model with additional feature to create different sets of wait. A Condition object is always created by Lock object. Some of the important methods are await() that is similar to wait() and signal(), signalAll() that is similar to notify() and notifyAll() methods.
    3. ReadWriteLock: It contains a pair of associated locks, one for read-only operations and another one for writing. The read lock may be held simultaneously by multiple reader threads as long as there are no writer threads. The write lock is exclusive.
    4. ReentrantLock: This is the most widely used implementation class of Lock interface. This class implements the Lock interface in similar way as synchronized keyword. Apart from Lock interface implementation, ReentrantLock contains some utility methods to get the thread holding the lock, threads waiting to acquire the lock etc.

      synchronized block are reentrant in nature i.e if a thread has lock on the monitor object and if another synchronized block requires to have the lock on the same monitor object then thread can enter that code block. I think this is the reason for the class name to be ReentrantLock. Let’s understand this feature with a simple example.

      
      public class Test{
      

      public synchronized foo(){
      //do something
      bar();
      }

      public synchronized bar(){
      //do some more
      }
      }

      If a thread enters foo(), it has the lock on Test object, so when it tries to execute bar() method, the thread is allowed to execute bar() method since it’s already holding the lock on the Test object i.e same as synchronized(this).

    Java Lock Example – ReentrantLock in Java

    Now let’s see a simple example where we will replace synchronized keyword with Java Lock API.

    Let’s say we have a Resource class with some operation where we want it to be thread-safe and some methods where thread safety is not required.

    Copy
    package com.journaldev.threads.lock;

    public class Resource {

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>)</span>{
    	<span class="hljs-comment">//do some operation, DB read, write etc</span>
    }
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doLogging</span>(<span class="hljs-params"></span>)</span>{
    	<span class="hljs-comment">//logging, no need for thread safety</span>
    }
    

    }

    Now let’s say we have a Runnable class where we will use Resource methods.

    
    package com.journaldev.threads.lock;
    

    public class SynchronizedLockExample implements Runnable{

    <span class="hljs-keyword">private</span> Resource resource;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SynchronizedLockExample</span><span class="hljs-params">(Resource r)</span></span>{
    	<span class="hljs-keyword">this</span>.resource = r;
    }
    
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
    	<span class="hljs-keyword">synchronized</span> (resource) {
    		resource.doSomething();
    	}
    	resource.doLogging();
    }
    

    }

    Notice that I am using synchronized block to acquire the lock on Resource object. We could have created a dummy object in the class and used that for locking purpose.

    Now let’s see how we can use java Lock API and rewrite above program without using synchronized keyword. We will use ReentrantLock in java.

    
    package com.journaldev.threads.lock;
    

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

    public class ConcurrencyLockExample implements Runnable{

    <span class="hljs-keyword">private</span> Resource resource;
    <span class="hljs-keyword">private</span> Lock lock;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ConcurrencyLockExample</span><span class="hljs-params">(Resource r)</span></span>{
    	<span class="hljs-keyword">this</span>.resource = r;
    	<span class="hljs-keyword">this</span>.lock = <span class="hljs-keyword">new</span> ReentrantLock();
    }
    
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
    	<span class="hljs-keyword">try</span> {
    		<span class="hljs-keyword">if</span>(lock.tryLock(<span class="hljs-number">10</span>, TimeUnit.SECONDS)){
    		resource.doSomething();
    		}
    	} <span class="hljs-keyword">catch</span> (InterruptedException e) {
    		e.printStackTrace();
    	}<span class="hljs-keyword">finally</span>{
    		<span class="hljs-comment">//release lock</span>
    		lock.unlock();
    	}
    	resource.doLogging();
    }
    

    }

    As you can see that, I am using tryLock() method to make sure my thread waits only for definite time and if it’s not getting the lock on object, it’s just logging and exiting. Another important point to note is the use of try-finally block to make sure lock is released even if doSomething() method call throws any exception.

    Java Lock vs synchronized

    Based on above details and program, we can easily conclude following differences between Java Lock and synchronization.

    1. Java Lock API provides more visibility and options for locking, unlike synchronized where a thread might end up waiting indefinitely for the lock, we can use tryLock() to make sure thread waits for specific time only.
    2. Synchronization code is much cleaner and easy to maintain whereas with Lock we are forced to have try-finally block to make sure Lock is released even if some exception is thrown between lock() and unlock() method calls.
    3. synchronization blocks or methods can cover only one method whereas we can acquire the lock in one method and release it in another method with Lock API.
    4. synchronized keyword doesn’t provide fairness whereas we can set fairness to true while creating ReentrantLock object so that longest waiting thread gets the lock first.
    5. We can create different conditions for Lock and different thread can await() for different conditions.

    That’s all for Java Lock example, ReentrantLock in java and a comparative analysis with synchronized keyword.

  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/jpfss/p/9373276.html
Copyright © 2020-2023  润新知