-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
SpinLockMutex.java
52 lines (43 loc) · 1.42 KB
/
SpinLockMutex.java
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
package nallar.tickthreading.util.concurrent;
import nallar.unsafe.UnsafeAccess;
import sun.misc.Unsafe;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public final class SpinLockMutex implements Lock {
private static final Unsafe $ = UnsafeAccess.$;
private static final long index = $.objectFieldOffset(SpinLockMutex.class.getFields()[0]);
private volatile int locked = 0;
@Override
public synchronized void lock() {
//noinspection StatementWithEmptyBody
while (!$.compareAndSwapInt(this, index, 0, 1)) {
// Spin lock.
// TODO: Could we instead work on something else here?
// Avoids overhead of OS scheduling without doing nothing
// might not be worth the effort to get it working correctly
}
}
@Override
public synchronized void unlock() {
if (locked == 0) {
throw new IllegalStateException("Unlocked " + this + " before it was locked.");
}
locked = 0;
}
@Override
public synchronized boolean tryLock() {
return $.compareAndSwapInt(this, index, 0, 1);
}
@Override
public synchronized void lockInterruptibly() throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException();
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
}