1 /*
2  * Copyright (C) 2015 Square, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package leakcanary
17 
18 import leakcanary.KeyedWeakReference.Companion.heapDumpUptimeMillis
19 import java.lang.ref.ReferenceQueue
20 import java.lang.ref.WeakReference
21 
22 /**
23  * A weak reference used by [ObjectWatcher] to determine which objects become weakly reachable
24  * and which don't. [ObjectWatcher] uses [key] to keep track of [KeyedWeakReference] instances that
25  * haven't made it into the associated [ReferenceQueue] yet.
26  *
27  * [heapDumpUptimeMillis] should be set with the current time from [Clock.uptimeMillis] right
28  * before dumping the heap, so that we can later determine how long an object was retained.
29  */
30 class KeyedWeakReference(
31   referent: Any,
32   val key: String,
33   val description: String,
34   val watchUptimeMillis: Long,
35   referenceQueue: ReferenceQueue<Any>
36 ) : WeakReference<Any>(
37   referent, referenceQueue
38 ) {
39   /**
40    * Time at which the associated object ([referent]) was considered retained, or -1 if it hasn't
41    * been yet.
42    */
43   @Volatile
44   var retainedUptimeMillis = -1L
45 
clearnull46   override fun clear() {
47     super.clear()
48     retainedUptimeMillis = -1L
49   }
50 
51   companion object {
52     @Volatile
53     @JvmStatic var heapDumpUptimeMillis = 0L
54   }
55 }
56