Concurrent issue:about read write lock
For the following testing code,how to make the read thread can automatically be notified when the write thread finishes writing new data to the container.
In order to improve the performance of concurrent reading data, read lock and write lock are used in the programme,beacause of this,I feel difficult to implement both of threads communicate with each other.
Anybody can provide a solution to reach the objective? Please note the pre-condition: don't use another lock to replace my read-write lock,if so,concurrent performance will be reduced.That's not what I need.
Thanks a lot in advance.
------------------------------------------------------------------------------------------
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
public class ReadWriteLockTest {
private ArrayList<String> container = new ArrayList<String>();
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private ReadLock readLock = readWriteLock.readLock();
private WriteLock writeLock = readWriteLock.writeLock();
public void execute(){
for(int k=0;k<1;k++){
Thread writeThread = new Thread(new Runnable(){
@Override
public void run() {
while(true){
writeLock.lock();
try{
for(int j = 0;j<3;j++){
container.add("_"+j);
}
System.out.println(Thread.currentThread().getName()+" write size:"+container.size());
}
finally{
writeLock.unlock();
}
try {
System.out.println(Thread.currentThread().getName()+" sleeping...");
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
writeThread.start();
}
for(int x=0;x<2;x++){
Thread readThread = new Thread(new Runnable(){
@Override
public void run() {
while(true){
readLock.lock();
try{
TimeUnit.SECONDS.sleep(1);
while(container.size()>0){
String str = container.get(0);
synchronized(container){ // remove operation need exclusive lock when read-read
container.remove(str);
}
System.out.println(Thread.currentThread().getName()+" read data:"+str+ " size:"+ container.size());
}
} catch (Exception e){
e.printStackTrace();
}finally{
readLock.unlock();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
readThread.start();
}
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws Exception {
ReadWriteLockTest test = new ReadWriteLockTest();
test.execute();
TimeUnit.SECONDS.sleep(100000);
}
}