ReentrantReadWriteLock

Language/JAVA 2014. 4. 16. 15:30

Example of ReentrantReadWriteLock in Java

December 17, 2012

ReentrantReadWriteLock implements ReadWriteLock which has both type of lock read lock and write lock. More than one thread can apply read lock simultaneously but write lock can be applied by one thread at one time. As an example of lock is that collection that is being accessed by more than one thread may need to modify the collection frequently. So threads will need to apply locks on that collection object. ReadWriteLock has only two method readLock and writeLock. readLock() is used for reading and writeLock() is used for writing. ReentrantReadWriteLock has the following properties.
1. ReentrantReadWriteLock has no preferences over the selection of readLock and writeLock. 
2. readLock cannot be acquired until all writeLock is released. 
3. It is possible to downgrade writeLock to readLock but vice-versa is not possible. 

Find the example of ReentrantReadWriteLock in a custom bean in concurrent environment. Let�s we have a MyBean class in which we have methods like add, get and delete.

  1. package com.concretepage;
  2.  
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantReadWriteLock;
  5.  
  6. public class MyBean {
  7. private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  8. private final Lock r = rwl.readLock();
  9. private final Lock w = rwl.writeLock();
  10. private String data;
  11.  
  12. public String getData() {
  13. r.lock();
  14. try{
  15. return data;
  16. }finally{
  17. r.unlock();
  18. }
  19. }
  20.  
  21. public void setData(String data) {
  22. w.lock();
  23. try{
  24. this.data = data;
  25. }finally{
  26. w.unlock();
  27. }
  28. }
  29. }

참조 - http://www.concretepage.com/java/example_readwriteLock_java

'Language > JAVA' 카테고리의 다른 글

pageContext 내장 객체  (0) 2014.11.11
http://www.docjar.com/  (0) 2014.11.11
한글, 유니코드의 이해  (0) 2014.01.14
정적 변수 정적 메소드 (static)  (1) 2014.01.07
Java에서 System.getProperty()  (2) 2014.01.02
: