樂觀鎖是一種并發(fā)控制策略,適用于讀多寫少的場景。它假設(shè)多個(gè)線程在訪問數(shù)據(jù)時(shí)不會發(fā)生沖突,因此不會立即加鎖,而是在更新數(shù)據(jù)時(shí)檢查數(shù)據(jù)是否被其他線程修改。如果數(shù)據(jù)被修改,則更新失敗,需要重新嘗試操作。Java中樂觀鎖的實(shí)現(xiàn)通常依賴于版本號或時(shí)間戳。
以下是使用版本號實(shí)現(xiàn)樂觀鎖的示例:
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. 查詢當(dāng)前數(shù)據(jù)及其版本號
Example example = exampleDao.findById(id);
if (example == null || example.getVersion() != currentVersion.getValue()) {
return false; // 數(shù)據(jù)不存在或版本號不一致,更新失敗
}
// 2. 更新數(shù)據(jù)
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;
}
通過這種方式,當(dāng)多個(gè)線程同時(shí)讀取數(shù)據(jù)并嘗試更新時(shí),只有第一個(gè)線程能夠成功更新數(shù)據(jù),其他線程會因?yàn)榘姹咎柌灰恢露率?,從而保證了數(shù)據(jù)的一致性。