1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package info.magnolia.cache.concurrent;
17
18 import java.util.concurrent.locks.ReentrantReadWriteLock;
19 import java.util.concurrent.locks.Lock;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.locks.ReadWriteLock;
22
23
24
25
26
27
28 public class ReadWriteLockSync {
29
30 private final ReentrantReadWriteLock rrwl;
31
32
33
34
35 public ReadWriteLockSync() {
36 this(new ReentrantReadWriteLock());
37 }
38
39
40
41
42
43 public ReadWriteLockSync(ReentrantReadWriteLock lock) {
44 this.rrwl = lock;
45 }
46
47
48
49 public void lock(final LockType type) {
50 getLock(type).lock();
51 }
52
53
54
55
56 public boolean tryLock(final LockType type, final long msec) throws InterruptedException {
57 return getLock(type).tryLock(msec, TimeUnit.MILLISECONDS);
58 }
59
60
61
62
63 public void unlock(final LockType type) {
64 getLock(type).unlock();
65 }
66
67 private Lock getLock(final LockType type) {
68 switch (type) {
69 case READ:
70 return rrwl.readLock();
71 case WRITE:
72 return rrwl.writeLock();
73 default:
74 throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
75 }
76 }
77
78
79
80
81
82
83 public ReadWriteLock getReadWriteLock() {
84 return rrwl;
85 }
86
87
88
89
90 public boolean isHeldByCurrentThread(LockType type) {
91 switch (type) {
92 case READ:
93 throw new UnsupportedOperationException("Querying of read lock is not supported.");
94 case WRITE:
95 return rrwl.isWriteLockedByCurrentThread();
96 default:
97 throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
98 }
99 }
100 }