我在主线程中有以下方法,它在我的数据结构上调用一个方法,如下所示:
public static void main(String[] args){
data_structure_object.insert(value);
}
我正在使用一个ReadWrite对象在数据结构类中调用它rwLock用于防止线程干扰,Read Write类如下所示 - :
public class ReadWriteLocks {
// these 3 variables help in creating a read write lock
private int numberOfReaders = 0;
private int numberOfWriters = 0;
private int numberOfWriteRequests = 0;
// getter method for the number of readers
public int getNumberOfReaders() {
return this.numberOfReaders;
}
// getter method for the number of writers
public int getNumberOfWriters() {
return this.numberOfWriters;
}
// getter method for the number of write requests
public int getNumberOfWriteRequests() {
return this.numberOfWriteRequests;
}
// this function checks if a thread can acquire the lock
public synchronized void lockRead() throws InterruptedException {
while (numberOfWriters > 0 || numberOfWriteRequests > 0)
this.wait();
}
// this function unlocks a lock occupied by a reader thread
public synchronized void unlockRead() {
// decrement the number of readers
--numberOfReaders;
notifyAll();
}
// this function checks if a thread can acquire the write lock
public synchronized void lockWrite() throws InterruptedException {
// increase the number of write requests
++numberOfWriteRequests;
while (numberOfReaders > 0 || numberOfWriters > 0)
this.wait();
--numberOfWriteRequests;
++numberOfWriters;
}
// this function is used to take a thread away from the lock
public synchronized void unlockWrite() {
// decrement the number of writers
--numberOfWriters;
// notify all the threads
this.notifyAll();
}
}
并且在数据结构的insert方法中,我包含以下代码片段
// acquire the read/write lock
try {
rwLock.lockRead();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Some operation
// release the lock
rwLock.unlockRead();
问题是,这是否是确保公平性和锁定线程以保持数据结构一致性的有效方法?除此之外,我无法弄清楚如何提供以下功能 - “允许多个读者获取锁定并读取数据,直到没有作者请求或写入资源”,我很困惑这种情况很有帮助。
答案 0 :(得分:0)
除了您尝试复制完全正常的ReadWriteLock
冒充ReentrantReadWriteLock
之外,您的代码中还存在两个问题:
您的实例变量应为volatile
。
private volatile int numberOfReaders = 0;
private volatile int numberOfWriters = 0;
private volatile int numberOfWriteRequests = 0;
您需要注意从锁定请求到锁定的转换。
--numberOfWriteRequests;
++numberOfWriters;
可能应该是
++numberOfWriters;
--numberOfWriteRequests;
因为当numberOfWriteRequests
为零且numberOfWriters
为零时,这两条指令之间可能存在片刻。这会让你的旋转循环在lockRead
中,事情会破坏......有时。
您可能最好将其移至代码审核中。