1 /* 2 * Copyright (C) 2017 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 com.android.systemui.util.leak; 18 19 import static org.junit.Assert.assertEquals; 20 import static org.junit.Assert.assertNotSame; 21 import static org.junit.Assert.assertTrue; 22 23 import android.support.test.filters.SmallTest; 24 import android.support.test.runner.AndroidJUnit4; 25 26 import com.android.systemui.SysuiTestCase; 27 import com.android.systemui.util.leak.ReferenceTestUtils.CollectionWaiter; 28 29 import org.junit.Before; 30 import org.junit.Test; 31 import org.junit.runner.RunWith; 32 33 @SmallTest 34 @RunWith(AndroidJUnit4.class) 35 public class WeakIdentityHashMapTest extends SysuiTestCase { 36 37 WeakIdentityHashMap<Object, Object> mMap; 38 39 @Before 40 public void setup() { 41 mMap = new WeakIdentityHashMap<>(); 42 } 43 44 private CollectionWaiter addObjectToMap(WeakIdentityHashMap<Object, Object> map) { 45 Object object = new Object(); 46 CollectionWaiter collectionWaiter = ReferenceTestUtils.createCollectionWaiter(object); 47 map.put(object, "value"); 48 return collectionWaiter; 49 } 50 51 @Test 52 public void testUsesIdentity() { 53 String a1 = new String("a"); 54 String a2 = new String("a"); 55 assertNotSame(a1, a2); 56 57 mMap.put(a1, "value1"); 58 mMap.put(a2, "value2"); 59 60 assertEquals("value1", mMap.get(a1)); 61 assertEquals("value2", mMap.get(a2)); 62 } 63 64 @Test 65 public void testWeaklyReferences() { 66 // Allocate and add an object to the weak map in a separate method to avoid a live 67 // reference to the allocated object in a dex register. As R8 is used to compile this 68 // test the --dontoptimize flag is also required to ensure that the method is not 69 // inlined, as that would defeat the purpose of having the allocation in a separate 70 // method. 71 CollectionWaiter collectionWaiter = addObjectToMap(mMap); 72 73 // Wait until object has been collected. We'll also need to wait for mMap to become empty, 74 // because our collection waiter may be told about the collection earlier than mMap. 75 collectionWaiter.waitForCollection(); 76 ReferenceTestUtils.waitForCondition(mMap::isEmpty); 77 78 assertEquals(0, mMap.size()); 79 assertTrue(mMap.isEmpty()); 80 } 81 } 82