Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Sunday, 21 July 2013

Java 5 Concurrency: Reader-Writer Locks

As long as threads are only reading and not writing to shared data, they can run in parallel without any serious issues. The java.util.concurrent.locks package provides classes that implement this type of locking. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock() may be held simultaneously by multiple reader threads, while the writeLock() is exclusive. While this implementation improves performance when compared to the mutex locks, it also depends on other factors,
  • Requires a multi-processor system
  • The frequency of reads as compared to that of writes. A higher frequency of reads is more suitable.
  • Duration of reads as compared to that of writes. Read duration has to be longer, as short reads mean that the readLock will become an overhead.
  • Contention for the data, i.e. the number of threads that will try to read or write the data at the same time
Skip to Sample Code
The following are a few issues to be considered while creating a ReadWriteLock
  • Whether to grant the read lock or the write lock the priority.
  • Whether readers that request the read lock while a reader is active and a writer is waiting.
  • Whether the locks are reentrant.
  • Can the write lock be downgraded to a read lock without allowing an intervening writer?
  • Can a read lock be upgraded to a write lock, in preference to other waiting readers or writers?
The ReentrantReadWriteLock is an implementation of ReadWriteLock with similar semantics to ReentrantLock. The following is a list of properties of the ReentrantReadWriteLock.
  • Acquisition order: Does not impose a reader or writer preference ordering for lock access.
    • When constructed as fair, threads contend for entry using an approximately arrival-order policy.
    • When the write lock is released either the longest-waiting single writer will be assigned the write lock, or if there is a reader waiting longer than any writer, the set of readers will be assigned the read lock.

    • When constructed as non-fair, the order of entry to the lock need not be in arrival order.
    • if readers are active and a writer enters the lock then no subsequent readers will be granted the read lock until after that writer has acquired and released the write lock.
  • Reentrancy: Allows both readers and writers to reacquire read or write locks in the style of a ReentrantLock. A writer can acquire the read lock - but not vice-versa. If a reader tries to acquire the write lock it will never succeed.
  • Interruption of lock acquisition: The read lock and write lock both support interruption during lock acquisition.
  • Condition support: The write lock provides a Condition implementation that behaves in the same way, with respect to the write lock, as the one provided by ReentrantLock.newCondition(). The read lock does not support a Condition.
  • Instrumentation: Supports methods to determine whether locks are held or contended.
The following is Sample Code on how to use ReentrantReadWriteLock. In the example, a set of readers tries to print out an ArrayList represented by data, and a list of Writers tries to add data in to the list. The producer/consumer problem can be implemented by replacing the readers with consumers and writers with producers. Instead of just reading the list, the consumers will have to remove data from the list.
public class Data {
private List<String> names;
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

public Data() {
names = new ArrayList<String>();
}

public List<String> getNames() {
return names;
}

public void setNames(List<String> names) {
this.names = names;
}

public void add(String str) {
lock.writeLock().lock();
System.out.println("Writer: Number of threads waiting : " + lock.getQueueLength());

// This will alwas be 1.
System.out.println("Writer: Number of write locks waiting : " + lock.getWriteHoldCount());
names.add(str);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.writeLock().unlock();
}

public void readData() {
lock.readLock().lock();
System.out.println("Reader: Number of threads waiting : " + lock.getQueueLength());
System.out.println("Reader: Number of read locks : " + lock.getReadLockCount());
Iterator<String> iter = names.iterator();
while (iter.hasNext()) {
iter.next();
// System.out.println(iter.next());
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.readLock().unlock();
}
}
Data.java
public class ListReader implements Runnable {
Data myData;
public void run() {
for(int i = 0; i < 10; i++) {
myData.readData();
}
}

public ListReader(Data myData) {
super();
this.myData = myData;
}
}
ListReader.java
public class ListWriter implements Runnable {
Data myData;
public ListWriter(Data myData) {
super();
this.myData = myData;
}
public void run() {
for(int i = 0; i < 10; i++) {
myData.add(Thread.currentThread().getName() + " : " + i);
}
}
}
ListWriter.java
  public static void main(String[] args) {
ListReader[] readers = new ListReader[THREADS];
ListWriter[] writers = new ListWriter[THREADS];
Data data = new Data();
Thread[] threads = new Thread[THREADS * 2];
for (int i = 0; i < THREADS; i++) {
readers[i] = new ListReader(data);
writers[i] = new ListWriter(data);
threads[i] = new Thread(readers[i], "" + i);
threads[i + THREADS] = new Thread(writers[i], "" + i);
}

for (int i = 0; i < THREADS * 2; i++) {
threads[i].start();
}

for (int i = 0; i < THREADS * 2; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
ReadWriteLockTest.java

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...