`
DavyJones2010
  • 浏览: 148964 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java SE: Reader&Writer Using ReadLock&WriteLock

阅读更多

1) Reader&Writer Problem Intro

    1> Reader&Writer task may share a resource, say a DB.

    2> Many Reader may access a DB without fear of data corruption.

    3> Only one Writer may access a DB at a time.

    Read Access: If no threads are writing, and no threads have acquired the write access.

    Write Access: If no threads are reading or writing.

 

2) Read&Write Lock

    1> Read&Write Lock is especially useful for Reader&Writer Problem

         when there are many threads that read from a data structure and fewer threads that modify it. 

    2> It makes sense to allow shared access for the readers. And a writer must still have exclusive access.

 

3) Example

package edu.xmu.thread;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class ReadeWriteLockTest {
    public static void main(String[] args) {
	Calculator calculator = new Calculator(2);
	Thread reader = new Thread(new Reader(calculator));
	Thread reader2 = new Thread(new Reader(calculator));
	Thread writer = new Thread(new Writer(calculator));

	reader.start();
	reader2.start();
	writer.start();
    }
}

class Reader implements Runnable {
    Calculator calculator;

    public Reader(Calculator calculator) {
	super();
	this.calculator = calculator;
    }

    @Override
    public void run() {
	while (true) {
	    int sum = calculator.getSum();
	    System.out.println("Thread: " + Thread.currentThread()
		    + " finished getSum(), sum = " + sum);

	    try {
		Thread.sleep((long) (1000 * Math.random()));
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }

}

class Writer implements Runnable {
    Calculator calculator;

    public Writer(Calculator calculator) {
	super();
	this.calculator = calculator;
    }

    @Override
    public void run() {
	while (true) {
	    calculator.add((int) (10 * Math.random()));
	    try {
		Thread.sleep((long) (1000 * Math.random()));
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }

}

class Calculator {
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    ReadLock readLock;
    WriteLock writeLock;
    int sum;

    public Calculator(int sum) {
	super();
	this.sum = sum;
	readLock = readWriteLock.readLock();
	writeLock = readWriteLock.writeLock();
    }

    public void add(int i) {
	writeLock.lock();

	System.out.println("Thread: " + Thread.currentThread()
		+ " get into add(" + i + ")");
	try {
	    Thread.sleep((long) (1000 * Math.random()));
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
	sum += i;
	System.out.println("Thread: " + Thread.currentThread()
		+ " finished add(" + i + ")");
	writeLock.unlock();
    }

    public int getSum() {
	readLock.lock();
	System.out.println("Thread: " + Thread.currentThread()
		+ " get into getSum()");
	readLock.unlock();

	return sum;
    }

}

    Output:

Thread: Thread[Thread-0,5,main] get into getSum() // thread-0 got read lock
Thread: Thread[Thread-1,5,main] get into getSum() // thread-1 got read lock
Thread: Thread[Thread-0,5,main] finished getSum(), sum = 2 // thread-0 released read lock
Thread: Thread[Thread-1,5,main] finished getSum(), sum = 2 // thread-1 released read lock
Thread: Thread[Thread-2,5,main] get into add(4)  // thread-2 got write lock and no other write/read lock may be got before this write lock released
Thread: Thread[Thread-2,5,main] finished add(4)  // thread-2 released write lock and other write/read lock may be got again.
Thread: Thread[Thread-1,5,main] get into getSum()
Thread: Thread[Thread-0,5,main] get into getSum()
Thread: Thread[Thread-1,5,main] finished getSum(), sum = 6
Thread: Thread[Thread-0,5,main] finished getSum(), sum = 6
Thread: Thread[Thread-1,5,main] get into getSum()
Thread: Thread[Thread-1,5,main] finished getSum(), sum = 6
Thread: Thread[Thread-2,5,main] get into add(5)
Thread: Thread[Thread-2,5,main] finished add(5)
Thread: Thread[Thread-0,5,main] get into getSum()
Thread: Thread[Thread-1,5,main] get into getSum()
Thread: Thread[Thread-0,5,main] finished getSum(), sum = 11
Thread: Thread[Thread-1,5,main] finished getSum(), sum = 11
Thread: Thread[Thread-0,5,main] get into getSum()
Thread: Thread[Thread-0,5,main] finished getSum(), sum = 11
Thread: Thread[Thread-2,5,main] get into add(1)
Thread: Thread[Thread-2,5,main] finished add(1)
Thread: Thread[Thread-1,5,main] get into getSum()
Thread: Thread[Thread-1,5,main] finished getSum(), sum = 12
Thread: Thread[Thread-2,5,main] get into add(6)
Thread: Thread[Thread-2,5,main] finished add(6)
Thread: Thread[Thread-0,5,main] get into getSum()
Thread: Thread[Thread-0,5,main] finished getSum(), sum = 18

 

 

Reference Links:

1) http://www.cs.wustl.edu/~fredk/Courses/cs422/sp03/Lectures/concurrency2.pdf

2) http://tutorials.jenkov.com/java-concurrency/read-write-locks.html

3) http://java.dzone.com/news/java-concurrency-read-write-lo

 

 

0
0
分享到:
评论

相关推荐

    基于JAVA的搜索引擎 lucene-2.2.0

    Lock writeLock = directory.makeLock(IndexWriter.WRITE_LOCK_NAME); if (!writeLock.obtain(writeLockTimeout)) // 获取写锁文件 throw new LockObtainFailedException("Index locked for write: " + writeLock...

    java-seqlock:一个简单,紧凑的Java SeqLock实现

    Java SeqLock 一个简单,紧凑的Java SeqLock实现。 实现细节来自David Dice的Weblog [here] [1]。 这是几年前我的SO [post] [2]上改进的SeqLock实现。用法读者线程: for (;;) {final long status = seqLock . ...

    JavaExamples:存储库包含小型Java项目和示例,作为常见问题(例如设计模式,并发问题等)的解决方案

    Java实例 Java示例和常见问题的解决方案。 ReaderWriter问题 并发实现常见计算问题。 使用了ReadWriteLock两个用于写和读的相关锁。 Writer线程: public void run() { while ( true ) { lock . writeLock() ....

    java多线程安全性基础介绍.pptx

    java多线程安全性基础介绍 线程安全 正确性 什么是线程安全性 原子性 竞态条件 i++ 读i ++ 值写回i 可见性 JMM 由于cpu和内存加载速度的差距,在两者之间增加了多级缓存导致,内存并不能直接对cpu可见。 ...

    共享锁using范围的实现方法

    IDisposable readLock, writeLock; public IDisposable ReadLock { get { Lock.AcquireReaderLock(-1); return readLock; } } public IDisposable WriteLock { get { Lock.AcquireWriterLock(-1); return writeLock...

    read-write-lock:读与写互斥,写与所有事物互斥

    读写锁 写锁可防止所有其他写或读 读锁只能阻止写操作 基于! 算法 写锁定请求被放入队列并按顺序分发。 读取锁定请求也被放入队列中-但是,当给出一个读取锁定时,队列中的... readLock ( function ( release ) {

    BucketHashMap

    如果这样的话,只会迫使您实现2个方法public Lock readLock(){return null; } public Lock writeLock() { return null;}I am then supposed to to return a lock which i use in the 4 provided methods within ...

    多线程编程-使用同步对象编程

    1、互斥锁(mutex)2、条件变量(conditionvariable)3、多读单写锁(multi-read,single-writelock) 4、信号量(semophore)5、进程间同步(processsynchronization)6、同步原语的比较(compareprimitive)同步对象是内存中...

Global site tag (gtag.js) - Google Analytics