1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
20 import java.util.concurrent.locks.Condition;
21 import java.util.concurrent.locks.Lock;
22
23
24
25
26
27
28 public final class NonReentrantLock extends AbstractQueuedSynchronizer
29 implements Lock {
30
31 private static final long serialVersionUID = -833780837233068610L;
32
33 private Thread owner;
34
35 public void lock() {
36 acquire(1);
37 }
38
39 public void lockInterruptibly() throws InterruptedException {
40 acquireInterruptibly(1);
41 }
42
43 public boolean tryLock() {
44 return tryAcquire(1);
45 }
46
47 public boolean tryLock(long time, TimeUnit unit)
48 throws InterruptedException {
49 return tryAcquireNanos(1, unit.toNanos(time));
50 }
51
52 public void unlock() {
53 release(1);
54 }
55
56 public boolean isHeldByCurrentThread() {
57 return isHeldExclusively();
58 }
59
60 public Condition newCondition() {
61 return new ConditionObject();
62 }
63
64 @Override
65 protected final boolean tryAcquire(int acquires) {
66 if (compareAndSetState(0, 1)) {
67 owner = Thread.currentThread();
68 return true;
69 }
70 return false;
71 }
72
73 @Override
74 protected final boolean tryRelease(int releases) {
75 if (Thread.currentThread() != owner) {
76 throw new IllegalMonitorStateException();
77 }
78 owner = null;
79 setState(0);
80 return true;
81 }
82
83 @Override
84 protected final boolean isHeldExclusively() {
85 return getState() != 0 && owner == Thread.currentThread();
86 }
87 }