/
FineGrainedISMLocking.java
397 lines (357 loc) · 12.5 KB
/
FineGrainedISMLocking.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.state;
import static org.apache.jackrabbit.core.TransactionContext.getCurrentThreadId;
import static org.apache.jackrabbit.core.TransactionContext.isSameThreadId;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.jackrabbit.core.id.ItemId;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.id.PropertyId;
import EDU.oswego.cs.dl.util.concurrent.Latch;
import EDU.oswego.cs.dl.util.concurrent.ReadWriteLock;
import EDU.oswego.cs.dl.util.concurrent.Sync;
import EDU.oswego.cs.dl.util.concurrent.WriterPreferenceReadWriteLock;
/**
* <code>FineGrainedISMLocking</code>...
*/
public class FineGrainedISMLocking implements ISMLocking {
/**
* Avoid creating commonly used Integer instances.
*/
private static final Integer ONE = new Integer(1);
/**
* An anonymous read lock without an id assigned.
*/
private final ReadLock anonymousReadLock = new ReadLockImpl();
/**
* The active writer or <code>null</code> if there is none.
*/
private WriteLockImpl activeWriter;
private volatile Object activeWriterId;
private ReadWriteLock writerStateRWLock = new WriterPreferenceReadWriteLock();
/**
* Map that contains the read locks.
*/
private final LockMap readLockMap = new LockMap();
/**
* List of waiting readers that are blocked because they conflict with
* the current writer.
*/
private List waitingReaders = Collections.synchronizedList(new LinkedList());
/**
* List of waiting writers that are blocked because there is already a
* current writer or one of the current reads conflicts with the change log
* of the blocked writer.
*/
private List waitingWriters = new LinkedList();
/**
* {@inheritDoc}
*/
public ReadLock acquireReadLock(ItemId id)
throws InterruptedException {
if (isSameThreadId(activeWriterId, getCurrentThreadId())) {
// we hold the write lock
readLockMap.addLock(id);
return new ReadLockImpl(id);
}
// if we get here the following is true:
// - the current thread does not hold a write lock
for (;;) {
Sync signal;
// make sure writer state does not change
Sync shared = writerStateRWLock.readLock();
shared.acquire();
try {
if (activeWriter == null
|| !hasDependency(activeWriter.changes, id)) {
readLockMap.addLock(id);
return new ReadLockImpl(id);
} else {
signal = new Latch();
waitingReaders.add(signal);
}
} finally {
shared.release();
}
// if we get here there was an active writer with
// a dependency to the current id.
// wait for the writer until it is done, then try again
signal.acquire();
}
}
/**
* {@inheritDoc}
*/
public WriteLock acquireWriteLock(ChangeLog changeLog)
throws InterruptedException {
for (;;) {
Sync signal;
// we want to become the current writer
Sync exclusive = writerStateRWLock.writeLock();
exclusive.acquire();
try {
if (activeWriter == null
&& !readLockMap.hasDependency(changeLog)) {
activeWriter = new WriteLockImpl(changeLog);
activeWriterId = getCurrentThreadId();
return activeWriter;
} else {
signal = new Latch();
waitingWriters.add(signal);
}
} finally {
exclusive.release();
}
// if we get here there is an active writer or there is a read
// lock that conflicts with the change log
signal.acquire();
}
}
//----------------------------< internal >----------------------------------
private final class WriteLockImpl implements WriteLock {
private final ChangeLog changes;
WriteLockImpl(ChangeLog changes) {
this.changes = changes;
}
public void release() {
Sync exclusive = writerStateRWLock.writeLock();
for (;;) {
try {
exclusive.acquire();
break;
} catch (InterruptedException e) {
// try again
Thread.interrupted();
}
}
try {
activeWriter = null;
activeWriterId = null;
notifyWaitingReaders();
notifyWaitingWriters();
} finally {
exclusive.release();
}
}
public ReadLock downgrade() {
readLockMap.addLock(null);
Sync exclusive = writerStateRWLock.writeLock();
for (;;) {
try {
exclusive.acquire();
break;
} catch (InterruptedException e) {
// try again
Thread.interrupted();
}
}
try {
activeWriter = null;
// only notify waiting readers since we still hold a down
// graded lock, which is kind of exclusiv with respect to
// other writers
notifyWaitingReaders();
} finally {
exclusive.release();
}
return anonymousReadLock;
}
}
private final class ReadLockImpl implements ReadLock {
private final ItemId id;
public ReadLockImpl() {
this(null);
}
ReadLockImpl(ItemId id) {
this.id = id;
}
public void release() {
Sync shared = writerStateRWLock.readLock();
for (;;) {
try {
shared.acquire();
break;
} catch (InterruptedException e) {
// try again
Thread.interrupted();
}
}
try {
readLockMap.removeLock(id);
if (!isSameThreadId(activeWriterId, getCurrentThreadId())) {
// only notify waiting writers if we do *not* hold a write
// lock at the same time. that would be a waste of cpu time.
notifyWaitingWriters();
}
} finally {
shared.release();
}
}
}
private static boolean hasDependency(ChangeLog changeLog, ItemId id) {
try {
if (changeLog.get(id) == null) {
if (!id.denotesNode() || changeLog.getReferencesTo((NodeId) id) == null) {
// change log does not contain the item
return false;
}
}
} catch (NoSuchItemStateException e) {
// is deleted
}
return true;
}
/**
* This method is not thread-safe and calling threads must ensure that
* only one thread calls this method at a time.
*/
private void notifyWaitingReaders() {
Iterator it = waitingReaders.iterator();
while (it.hasNext()) {
((Sync) it.next()).release();
it.remove();
}
}
/**
* This method may be called concurrently by multiple threads.
*/
private void notifyWaitingWriters() {
synchronized (waitingWriters) {
if (waitingWriters.isEmpty()) {
return;
}
Iterator it = waitingWriters.iterator();
while (it.hasNext()) {
((Sync) it.next()).release();
it.remove();
}
}
}
private static final class LockMap {
/**
* 16 slots
*/
private final Map[] slots = new Map[0x10];
/**
* Flag that indicates if the entire map is locked.
*/
private volatile boolean global = false;
public LockMap() {
for (int i = 0; i < slots.length; i++) {
slots[i] = new HashMap();
}
}
/**
* This method must be called while holding the reader sync of the
* {@link FineGrainedISMLocking#writerStateRWLock}!
*
* @param id the item id.
*/
public void addLock(ItemId id) {
if (id == null) {
if (global) {
throw new IllegalStateException(
"Map already globally locked");
}
global = true;
return;
}
Map locks = slots[slotIndex(id)];
synchronized (locks) {
Integer i = (Integer) locks.get(id);
if (i == null) {
i = ONE;
} else {
i = new Integer(i.intValue() + 1);
}
locks.put(id, i);
}
}
/**
* This method must be called while holding the reader sync of the
* {@link FineGrainedISMLocking#writerStateRWLock}!
*
* @param id the item id.
*/
public void removeLock(ItemId id) {
if (id == null) {
if (!global) {
throw new IllegalStateException(
"Map not globally locked");
}
global = false;
return;
}
Map locks = slots[slotIndex(id)];
synchronized (locks) {
Integer i = (Integer) locks.get(id);
if (i != null) {
if (i.intValue() == 1) {
locks.remove(id);
} else {
locks.put(id, new Integer(i.intValue() - 1));
}
} else {
throw new IllegalStateException(
"No lock present for id: " + id);
}
}
}
/**
* This method must be called while holding the write sync of {@link
* FineGrainedISMLocking#writerStateRWLock} to make sure no additional
* read locks are added to or removed from the map!
*
* @param changes the change log.
* @return if the change log has a dependency to the locks currently
* present in this map.
*/
public boolean hasDependency(ChangeLog changes) {
if (global) {
// read lock present, which was downgraded from a write lock
return true;
}
for (int i = 0; i < slots.length; i++) {
Map locks = slots[i];
if (!locks.isEmpty()) {
Iterator it = locks.keySet().iterator();
while (it.hasNext()) {
ItemId id = (ItemId) it.next();
if (FineGrainedISMLocking.hasDependency(changes, id)) {
return true;
}
}
}
}
return false;
}
private static int slotIndex(ItemId id) {
NodeId nodeId;
if (id.denotesNode()) {
nodeId = (NodeId) id;
} else {
nodeId = ((PropertyId) id).getParentId();
}
return ((int) nodeId.getLeastSignificantBits()) & 0xf;
}
}
}