1 /* 2 * Copyright (C) 2008 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 import java.lang.ref.*; 18 19 public class InternedString { 20 public static final String CONST = "Class InternedString"; 21 22 public static void run() { 23 System.out.println("InternedString.run"); 24 testImmortalInternedString(); 25 testDeadInternedString(); 26 } 27 28 private static void testDeadInternedString() { 29 String s = "blah"; 30 s = s + s; 31 WeakReference strRef = new WeakReference<String>(s.intern()); 32 // Kill s, otherwise the string object is still accessible from root set 33 s = CONST; 34 System.gc(); 35 // "blahblah" should disappear from the intern list 36 assert(strRef.get() == null); 37 } 38 39 private static void testImmortalInternedString() { 40 WeakReference strRef = new WeakReference<String>(CONST.intern()); 41 System.gc(); 42 // Class constant string should be entered to the interned table when 43 // loaded 44 assert(CONST == CONST.intern()); 45 // and it should survive the gc 46 assert(strRef.get() != null); 47 48 String s = CONST; 49 // "Class InternedString" should remain on the intern list 50 strRef = new WeakReference<String>(s.intern()); 51 // Kill s, otherwise the string object is still accessible from root set 52 s = ""; 53 System.gc(); 54 assert(strRef.get() == CONST); 55 } 56 } 57