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