我正在我的應用程式中使用 ArrayList 實作一個簡單的快取。
我想同步快取更新操作,同時更新快取我不應該允許執行讀取操作。所以一旦快取更新完成,那么只有快取應該允許讀取。
背景關系管理器.java
public class ContextManager{
private List<String> trashCanIds;
public List<String> getIds() {
return ids;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
}
配置管理器.java
public class ConfigManager{
ContextManager ctxManager = new ContextManager();
public synchronized List<String> loadIds() throws Exception {
Utils utils = new Utils();
List<String> listIds = null;
String[] ids = utils.fetchIds();
if(Objects.nonNull(ids) && ids.length > 0) {
listIds = new ArrayList<>(Arrays.asList(ids[0].split(",")));
}
ctxManager.setIds(idsList);
return idsList;
}
}
洗掉管理器.java
public class DeleteManager {
ConfigManager configManager = new ConfigManager();
configManager.loadIds();
}
測驗管理器.java
public class TestManager {
ContextManager contextManager = new ContextManager();
contextManager.getIds();
}
在這段代碼中,我同步了 loadIds() 方法。
需要幫助,如何防止在 loadIds() 進行時讀取 getIds()。
uj5u.com熱心網友回復:
您可以通過使用實體實作的ReadWriteLock介面來實作這一點。這個類可以通過在執行and操作ReentrantReadWriteLock時獲取相應的鎖來代表你的讀寫情況。實際上,getIdsloadIds
ReadWriteLock 維護一對關聯的鎖,一個用于只讀操作,一個用于寫入。只要沒有寫者,讀鎖可能被多個讀執行緒同時持有。寫鎖是獨占的。
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html
基本上,您loadIds應該在繼續操作之前獲取寫鎖。如果成功,則立即獲取鎖并繼續計算;否則它會阻塞相應的執行緒,直到獲得鎖或拋出 InterruptedException。
另一方面,該getIds方法應該獲取讀鎖。如果可用,當前執行緒立即獲得鎖;否則它會阻塞相應的執行緒,直到獲得鎖或拋出 InterruptedException。
背景關系管理器.java
public class ContextManager{
private List<String> trashCanIds;
private ReadWriteLock lock;
private Lock readLock;
private Lock writeLock;
public ContextManager(){
lock = new ReentrantReadWriteLock(true);
readLock = lock.readLock();
writeLock = lock.writeLock();
}
public List<String> getIds() {
readLock.lock();
try {
List<String> tempTrashCanIds = new ArrayList(trashCanIds);
} finally {
readLock.unlock();
}
return tempTrashCanIds;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
public void readLock(){
this.readLock.lock();
}
public void readUnlock(){
this.readLock.unlock();
}
public void writeLock(){
this.writeLock.lock();
}
public void writeUnlock(){
this.writeLock.unlock();
}
}
配置管理器.java
public class ConfigManager{
ContextManager ctxManager = new ContextManager();
public List<String> loadIds() throws Exception {
Utils utils = new Utils();
List<String> listIds = null;
String[] ids = utils.fetchIds();
if(Objects.nonNull(ids) && ids.length > 0) {
listIds = new ArrayList<>(Arrays.asList(ids[0].split(",")));
}
ctxManager.writeLock();
try {
ctxManager.setIds(idsList);
} finally {
ctxManager.writeUnlock();
}
return idsList;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467468.html
上一篇:多執行緒場景中的布爾屬性
