樂觀鎖是一種并發控制策略,適用于讀多寫少的場景。它假設多個線程在訪問數據時不會發生沖突,因此不會立即加鎖,而是在更新數據時檢查數據是否被其他線程修改。如果數據被修改,則更新失敗,需要重新嘗試操作。Java中樂觀鎖的實現通常依賴于版本號或時間戳。
以下是使用版本號實現樂觀鎖的示例:
version
)。CREATE TABLE example (
id INT PRIMARY KEY,
data VARCHAR(255),
version INT
);
Version
類表示版本號:public class Version {
private int value;
public Version(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public boolean updateData(int id, String newData, Version currentVersion) {
// 1. 查詢當前數據及其版本號
Example example = exampleDao.findById(id);
if (example == null || example.getVersion() != currentVersion.getValue()) {
return false; // 數據不存在或版本號不一致,更新失敗
}
// 2. 更新數據
example.setData(newData);
example.setVersion(example.getVersion() + 1);
exampleDao.update(example);
return true; // 更新成功
}
public Example readData(int id) {
Example example = exampleDao.findById(id);
if (example != null) {
example.setVersion(example.getVersion() + 1); // 更新版本號
}
return example;
}
通過這種方式,當多個線程同時讀取數據并嘗試更新時,只有第一個線程能夠成功更新數據,其他線程會因為版本號不一致而更新失敗,從而保證了數據的一致性。