blob: 8e1108006756913feec8363d2b9fee17ff0c27df (
plain) (
blame)
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
|
/*******************************************************************************
* Copyright (c) 2010 Google, Inc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sergey Prigogin (Google) - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.internal.core.pdom;
import org.eclipse.cdt.internal.core.index.IWritableIndex;
/**
* Write lock on the index that can be yielded temporarily to unblock threads that need
* read access to the index.
* @since 5.2
*/
public class YieldableIndexLock {
private final IWritableIndex index;
private final int readlockCount;
private final boolean flushIndex;
private long lastLockTime;
private long cumulativeLockTime;
public YieldableIndexLock(IWritableIndex index, int readlockCount, boolean flushIndex) {
this.index = index;
this.readlockCount = readlockCount;
this.flushIndex = flushIndex;
}
/**
* Acquires the lock.
*
* @throws InterruptedException
*/
public void acquire() throws InterruptedException {
index.acquireWriteLock(readlockCount);
lastLockTime = System.currentTimeMillis();
}
/**
* Releases the lock.
*/
public void release() {
if (lastLockTime != 0) {
index.releaseWriteLock(readlockCount, flushIndex);
cumulativeLockTime += System.currentTimeMillis() - lastLockTime;
lastLockTime = 0;
}
}
/**
* Yields the lock temporarily if it was held for YIELD_INTERVAL or more, and somebody is waiting
* for a read lock.
* @throws InterruptedException
*/
public void yield() throws InterruptedException {
if (index.hasWaitingReaders()) {
index.releaseWriteLock(readlockCount, false);
cumulativeLockTime += System.currentTimeMillis() - lastLockTime;
lastLockTime = 0;
acquire();
}
}
/**
* @return Total time the lock was held in milliseconds.
*/
public long getCumulativeLockTime() {
return cumulativeLockTime;
}
}
|