Skip to content

Instantly share code, notes, and snippets.

@dector
Last active May 13, 2019 23:23
Show Gist options
  • Save dector/803a7c5568f4824b0287538244fba1a5 to your computer and use it in GitHub Desktop.
Save dector/803a7c5568f4824b0287538244fba1a5 to your computer and use it in GitHub Desktop.
Heavy object for more sensitive memory leaking detection
package io.github.dector.tools
import android.util.Log
import java.lang.ref.WeakReference
/**
* Usage example: `class Foo : HeavyObject by HeavyObject.new() {`.
*/
interface HeavyObject {
companion object {
fun new(sizeBytes: Int = 1024 * 1024 * 50, debug: Boolean = true): HeavyObject =
HeavyObjectImpl(sizeBytes, debug)
}
}
private class HeavyObjectImpl(sizeBytes: Int, debug: Boolean) : HeavyObject {
private val TAG = "HeavyObject #${(this as Any).hashCode().toString(16)}"
init {
if (debug) {
log(TAG, "Allocating $sizeBytes bytes")
filterInstance()
log(TAG, "Before allocation can see ${instances.size} instances")
}
}
@Suppress("unused")
private val load = ByteArray(sizeBytes) { 1 }
init {
if (debug) {
instances.add(WeakReference(this))
log(TAG, "After allocation can see ${instances.size} instances")
}
}
private fun filterInstance() {
instances.removeAll { it.get() == null }
}
companion object {
private val instances = mutableListOf<WeakReference<HeavyObject>>()
}
}
@Suppress("NOTHING_TO_INLINE")
private inline fun log(tag: String, message: String) {
Log.w(tag, message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment