StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Wednesday, September 24, 2014

Java ReentrantReadWriteLock

 September 24, 2014     Java     No comments   

ReentrantReadWriteLock Introduction

A read-write lock provides greater level of concurrency than a mutual exclusion lock when working with shared data. Read-write locks allows simultaneous read only operations by multiple threads whereas a write operation can be performed by only one thread. Read-write locks provide increased level of concurrency and typically results in better performance if the frequency of read operations is more than write operations.

Java ReentrantReadWriteLock

Java supports ReadWriteLock interface in java.utils.concurrent.locks package. ReentrantReadWriteLock is an implementation of the ReadWriteLock interface. ReadWriteLock maintains a pair of locks one for read only operations and one for write operations. The read lock can be held by multiple threads simultaneously whereas a write lock can held only by one thread at a time. Some of the key APIs of ReentrantReadWriteLock are listed below.
  • ReentrantReadWriteLock() - Creates a new instance of  ReentrantReadWriteLock.
  • ReentrantReadWriteLock(boolean fair) - Creates a new instance of  ReentrantReadWriteLock with fairness policy.
  • ReentrantReadWriteLock.ReadLock readLock() - Returns lock used for reading.
  • ReentrantReadWriteLock.WriteLock writeLock() - Returns lock used for writing.

Java ReentrantReadWriteLock Example

In this example we have a producer task requesting for write lock and two reader tasks requesting for read lock. When write lock is provided both the reader threads are blocked. However both the reader threads work simultaneously since they request only for read locks.
package com.sourcetricks.readwritelock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
  
  // Shared resources to be guarded
  private static int count = 0;

  // Producer thread. Counts up the resource.
  private static class ProducerTask implements Runnable {

    private ReentrantReadWriteLock lock = null;

    ProducerTask(ReentrantReadWriteLock lock) {
      this.lock = lock;
    }

    @Override
    public void run() {
      System.out.println("Producer requesting lock");
      lock.writeLock().lock();
      System.out.println("Producer gets lock");
      for (int i = 0; i < 5; i++) {
        count = count + 1;
        System.out.println("Counting up");
      }
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Producer releases lock");
      lock.writeLock().unlock();
    }

  }

  // Reader task
  private static class AnotherReadTask implements Runnable {

    private ReentrantReadWriteLock lock = null;

    AnotherReadTask(ReentrantReadWriteLock lock) {
      this.lock = lock;
    }

    @Override
    public void run() {
      System.out.println("Another Reader requesting lock");
      lock.readLock().lock();
      System.out.println("Another Reader gets lock");
      System.out.println("Current count = " + count);
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Another Reader releases lock");
      lock.readLock().unlock();
    }
  }
  
  // Reader task
  private static class ReadTask implements Runnable {

    private ReentrantReadWriteLock lock = null;

    ReadTask(ReentrantReadWriteLock lock) {
      this.lock = lock;
    }
    
    @Override
    public void run() {
      System.out.println("Reader requesting lock");
      lock.readLock().lock();
      System.out.println("Reader gets lock");
      System.out.println("Current count = " + count);
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("Reader releases lock");
      lock.readLock().unlock();     
    }   
  }

  public static void main(String[] args) {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    Thread producer = new Thread(new ProducerTask(lock));
    Thread anotherReader = new Thread(new AnotherReadTask(lock));
    Thread reader = new Thread(new ReadTask(lock));
    producer.start();
    reader.start();
    anotherReader.start();
  }
}
This program produces the following output.
Producer requesting lock
Reader requesting lock
Producer gets lock
Counting up
Counting up
Counting up
Counting up
Counting up
Another Reader requesting lock
Producer releases lock
Reader gets lock
Current count = 5
Another Reader gets lock
Current count = 5
Reader releases lock
Another Reader releases lock
Refer to this link for more Java Tutorials.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk