-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimisticLock.java
More file actions
53 lines (47 loc) · 1.34 KB
/
OptimisticLock.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
package common_problem;
import sun.misc.Unsafe;
import java.io.Serializable;
/**
* 乐观锁
*
* @author JunjunYang
* @date 2020/1/8 21:46
*/
public class OptimisticLock {
/**
* 版本号实现
*
* @return
*/
static class AccountService {
public boolean transAccount(int delta) {
// "select version,account from account where id = A";
// compute account;
// "update account set account=#{account},version=version+1 where version=#{version} and id = A"
return true;
}
}
/**
* CAS实现
*/
static class AtomicInteger implements Serializable {
private volatile int value;
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception e) {
throw new Error(e);
}
}
public int increateAndGet() {
for (; ; ) {
int cur = value;
int next = value + 1;
if (unsafe.compareAndSwapInt(this, valueOffset, cur, next))
return next;
}
}
}
}