aboutsummaryrefslogtreecommitdiffstats
path: root/zkfacade/src/main/java/com/yahoo/vespa/curator/stats/ThreadLockInfo.java
blob: b796cb9af432b4c65b89ff6c856ab1d9272f5660 (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
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
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.curator.stats;

import com.yahoo.vespa.curator.Lock;

import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * This class contains process-wide statistics and information related to acquiring and releasing
 * {@link Lock}.  Instances of this class contain information tied to a specific thread and lock path.
 *
 * <p>Instances of this class are thread-safe as long as foreign threads (!= this.thread) avoid mutable methods.</p>
 *
 * @author hakon
 */
public class ThreadLockInfo {

    private static final ConcurrentHashMap<Thread, ThreadLockInfo> locks = new ConcurrentHashMap<>();

    private static final int MAX_COMPLETED_LOCK_INFOS_SIZE = 5;
    /** Would have used a thread-safe priority queue. */
    private static final Object completedLockInfosMonitor = new Object();
    private static final PriorityQueue<LockInfo> completedLockInfos =
            new PriorityQueue<>(Comparator.comparing(LockInfo::getDurationInTerminalStateAndForPriorityQueue));

    private static final ConcurrentHashMap<String, LockCounters> countersByLockPath = new ConcurrentHashMap<>();

    private final Thread thread;
    private final String lockPath;
    private final LockCounters lockCountersForPath;

    /** The locks are reentrant so there may be more than 1 lock for this thread. */
    private final ConcurrentLinkedQueue<LockInfo> lockInfos = new ConcurrentLinkedQueue<>();

    public static Map<String, LockCounters> getLockCountersByPath() { return Map.copyOf(countersByLockPath); }

    public static List<ThreadLockInfo> getThreadLockInfos() { return List.copyOf(locks.values()); }

    public static List<LockInfo> getSlowLockInfos() {
        synchronized (completedLockInfosMonitor) {
            return List.copyOf(completedLockInfos);
        }
    }

    /** Returns the per-thread singleton ThreadLockInfo. */
    public static ThreadLockInfo getCurrentThreadLockInfo(String lockPath) {
        return locks.computeIfAbsent(
                Thread.currentThread(),
                currentThread -> {
                    LockCounters lockCounters = countersByLockPath.computeIfAbsent(lockPath, ignored -> new LockCounters());
                    return new ThreadLockInfo(currentThread, lockPath, lockCounters);
                });
    }

    static void clearStaticDataForTesting() {
        locks.clear();
        completedLockInfos.clear();
        countersByLockPath.clear();
    }

    ThreadLockInfo(Thread currentThread, String lockPath, LockCounters lockCountersForPath) {
        this.thread = currentThread;
        this.lockPath = lockPath;
        this.lockCountersForPath = lockCountersForPath;
    }

    public String getThreadName() { return thread.getName(); }
    public String getLockPath() { return lockPath; }

    public String getStackTrace() {
        var stackTrace = new StringBuilder();

        StackTraceElement[] elements = thread.getStackTrace();
        for (int i = 0; i < elements.length; ++i) {
            var element = elements[i];
            stackTrace.append(element.getClassName())
                    .append('.')
                    .append(element.getMethodName())
                    .append('(')
                    .append(element.getFileName())
                    .append(':')
                    .append(element.getLineNumber())
                    .append(")\n");
        }

        return stackTrace.toString();
    }

    public List<LockInfo> getLockInfos() { return List.copyOf(lockInfos); }

    /** Mutable method (see class doc) */
    public void invokingAcquire(Duration timeout) {
        lockCountersForPath.invokeAcquireCount.incrementAndGet();
        lockCountersForPath.inCriticalRegionCount.incrementAndGet();
        lockInfos.add(LockInfo.invokingAcquire(this, timeout));
    }

    /** Mutable method (see class doc) */
    public void acquireFailed() {
        removeLastLockInfo(lockCountersForPath.acquireFailedCount, LockInfo::acquireFailed);
    }

    /** Mutable method (see class doc) */
    public void acquireTimedOut() {
        if (lockInfos.size() > 1) {
            lockCountersForPath.timeoutOnReentrancyErrorCount.incrementAndGet();
        }

        removeLastLockInfo(lockCountersForPath.acquireTimedOutCount, LockInfo::timedOut);
    }

    /** Mutable method (see class doc) */
    public void lockAcquired() {
        lockCountersForPath.lockAcquiredCount.incrementAndGet();

        getLastLockInfo().ifPresent(LockInfo::lockAcquired);
    }

    /** Mutable method (see class doc) */
    public void lockReleased() {
        removeLastLockInfo(lockCountersForPath.locksReleasedCount, LockInfo::released);
    }

    private Optional<LockInfo> getLastLockInfo() {
        return lockInfos.isEmpty() ? Optional.empty() : Optional.of(lockInfos.peek());
    }

    private void removeLastLockInfo(AtomicInteger metricToIncrement, Consumer<LockInfo> completeLockInfo) {
        metricToIncrement.incrementAndGet();
        lockCountersForPath.inCriticalRegionCount.decrementAndGet();

        if (lockInfos.isEmpty()) {
            lockCountersForPath.noLocksErrorCount.incrementAndGet();
            return;
        }

        LockInfo lockInfo = lockInfos.poll();
        completeLockInfo.accept(lockInfo);

        synchronized (completedLockInfosMonitor) {
            if (completedLockInfos.size() < MAX_COMPLETED_LOCK_INFOS_SIZE) {
                lockInfo.fillStackTrace();
                completedLockInfos.add(lockInfo);
            } else if (lockInfo.getDurationInTerminalStateAndForPriorityQueue()
                    .compareTo(completedLockInfos.peek().getDurationInTerminalStateAndForPriorityQueue()) > 0) {
                completedLockInfos.poll();
                lockInfo.fillStackTrace();
                completedLockInfos.add(lockInfo);
            }
        }
    }
}