- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimisticLock.java
More file actions
Latest commit
53 lines (47 loc) · 1.34 KB
/
Copy pathOptimisticLock.java
File metadata and controls
53 lines (47 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
packagecommon_problem;
importsun.misc.Unsafe;
importjava.io.Serializable;
/**
* 乐观锁
*
* @author JunjunYang
* @date 2020/1/8 21:46
*/
publicclassOptimisticLock {
/**
* 版本号实现
*
* @return
*/
staticclassAccountService {
publicbooleantransAccount(intdelta) {
// "select version,account from account where id = A";
// compute account;
// "update account set account=#{account},version=version+1 where version=#{version} and id = A"
returntrue;
}
}
/**
* CAS实现
*/
staticclassAtomicIntegerimplementsSerializable {
privatevolatileintvalue;
privatestaticfinalUnsafeunsafe = Unsafe.getUnsafe();
privatestaticfinallongvalueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
} catch (Exceptione) {
thrownewError(e);
}
}
publicintincreateAndGet() {
for (; ; ) {
intcur = value;
intnext = value + 1;
if (unsafe.compareAndSwapInt(this, valueOffset, cur, next))
returnnext;
}
}
}
}