1 /* <lambda>null2 * Copyright 2021 The Android Open Source Project 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 17 package androidx.paging 18 19 import androidx.kruth.assertWithMessage 20 import androidx.paging.internal.AtomicBoolean 21 import java.lang.ref.ReferenceQueue 22 import java.lang.ref.WeakReference 23 import kotlin.concurrent.thread 24 import kotlin.random.Random 25 import kotlin.reflect.KClass 26 import kotlin.time.Duration.Companion.seconds 27 28 internal class GarbageCollectionTestHelper { 29 private val queue = ReferenceQueue<Any>() 30 private val references = mutableListOf<WeakReference<Any>>() 31 private var size = 0 32 33 fun track(item: Any) { 34 references.add(WeakReference(item, queue)) 35 size++ 36 } 37 38 fun assertLiveObjects(vararg expected: Pair<KClass<*>, Int>) { 39 val continueTriggeringGc = AtomicBoolean(true) 40 thread { 41 val leak: ArrayList<ByteArray> = ArrayList() 42 do { 43 val arraySize = Random.nextInt(1000) 44 leak.add(ByteArray(arraySize)) 45 System.gc() 46 } while (continueTriggeringGc.get()) 47 } 48 var collectedItemCount = 0 49 val expectedItemCount = size - expected.sumOf { it.second } 50 while ( 51 collectedItemCount < expectedItemCount && 52 queue.remove(5.seconds.inWholeMilliseconds) != null 53 ) { 54 collectedItemCount++ 55 } 56 continueTriggeringGc.set(false) 57 val leakedObjects = countLiveObjects() 58 val leakedObjectToStrings = references.mapNotNull { it.get() }.joinToString("\n") 59 assertWithMessage("expected to collect $expectedItemCount, collected $collectedItemCount") 60 .that(collectedItemCount) 61 .isEqualTo(expectedItemCount) 62 assertWithMessage( 63 """ 64 expected to collect $expectedItemCount, collected $collectedItemCount. 65 live objects: $leakedObjectToStrings 66 """ 67 .trimIndent() 68 ) 69 .that(leakedObjects) 70 .containsExactlyElementsIn(expected) 71 } 72 73 /** Tries to trigger garbage collection until an element is available in the given queue. */ 74 fun assertEverythingIsCollected() { 75 assertLiveObjects() 76 } 77 78 private fun countLiveObjects(): List<Pair<KClass<*>, Int>> { 79 return references 80 .mapNotNull { it.get() } 81 .groupBy { it::class } 82 .map { entry -> entry.key to entry.value.size } 83 } 84 } 85