summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/util/leak/TrackedGarbage.java
blob: 98a6450800a3b250f9cba94efb40190e9865a8b0 (plain)
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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed 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 com.android.systemui.util.leak;

import android.os.SystemClock;
import android.util.ArrayMap;

import java.io.PrintWriter;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Map;

/**
 * Tracks objects that have been marked as garbage.
 */
public class TrackedGarbage {

    /** Duration after which we consider garbage to be old. */
    private static final long GARBAGE_COLLECTION_DEADLINE_MILLIS = 60000; // 1min

    private final HashSet<LeakReference> mGarbage = new HashSet<>();
    private final ReferenceQueue<Object> mRefQueue = new ReferenceQueue<>();
    private final TrackedCollections mTrackedCollections;

    public TrackedGarbage(TrackedCollections trackedCollections) {
        mTrackedCollections = trackedCollections;
    }

    /**
     * @see LeakDetector#trackGarbage(Object)
     */
    public synchronized void track(Object o) {
        cleanUp();
        mGarbage.add(new LeakReference(o, mRefQueue));
        mTrackedCollections.track(mGarbage, "Garbage");
    }

    private void cleanUp() {
        Reference<?> ref;
        while ((ref = mRefQueue.poll()) != null) {
            mGarbage.remove(ref);
        }
    }

    /**
     * A reference to something we consider leaked if it still has strong references.
     *
     * Helpful for finding potential leaks in a heapdump: Simply find an instance of
     * LeakReference, find the object it refers to, then find a strong path to a GC root.
     */
    private static class LeakReference extends WeakReference<Object> {
        private final Class<?> clazz;
        private final long createdUptimeMillis;

        LeakReference(Object t, ReferenceQueue<Object> queue) {
            super(t, queue);
            clazz = t.getClass();
            createdUptimeMillis = SystemClock.uptimeMillis();
        }
    }

    /**
     * Dump statistics about the garbage.
     *
     * For each class, dumps the number of "garbage objects" that have not been collected yet.
     * A large number of old instances indicates a probable leak.
     */
    public synchronized void dump(PrintWriter pw) {
        cleanUp();

        long now = SystemClock.uptimeMillis();

        ArrayMap<Class<?>, Integer> acc = new ArrayMap<>();
        ArrayMap<Class<?>, Integer> accOld = new ArrayMap<>();
        for (LeakReference ref : mGarbage) {
            acc.put(ref.clazz, acc.getOrDefault(ref.clazz, 0) + 1);
            if (isOld(ref.createdUptimeMillis, now)) {
                accOld.put(ref.clazz, accOld.getOrDefault(ref.clazz, 0) + 1);
            }
        }

        for (Map.Entry<Class<?>, Integer> entry : acc.entrySet()) {
            pw.print(entry.getKey().getName());
            pw.print(": ");
            pw.print(entry.getValue());
            pw.print(" total, ");
            pw.print(accOld.getOrDefault(entry.getKey(), 0));
            pw.print(" old");
            pw.println();
        }
    }

    public synchronized int countOldGarbage() {
        cleanUp();

        long now = SystemClock.uptimeMillis();

        int result = 0;
        for (LeakReference ref : mGarbage) {
            if (isOld(ref.createdUptimeMillis, now)) {
                result++;
            }
        }
        return result;
    }

    private boolean isOld(long createdUptimeMillis, long now) {
        return createdUptimeMillis + GARBAGE_COLLECTION_DEADLINE_MILLIS < now;
    }
}