Initial import
[jpf-core.git] / src / tests / gov / nasa / jpf / test / java / lang / ref / WeakReferenceTest.java
1 /*
2  * Copyright (C) 2014, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The Java Pathfinder core (jpf-core) platform is licensed under the
7  * Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  * 
10  *        http://www.apache.org/licenses/LICENSE-2.0. 
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and 
16  * limitations under the License.
17  */
18
19 package gov.nasa.jpf.test.java.lang.ref;
20
21 import gov.nasa.jpf.util.test.TestJPF;
22 import gov.nasa.jpf.vm.Verify;
23
24 import java.lang.ref.WeakReference;
25
26 import org.junit.Test;
27
28 public class WeakReferenceTest extends TestJPF
29 {
30    @Test
31    public void testGCClearsRef()
32    {
33       WeakReference<Target> ref;
34
35       if (verifyNoPropertyViolation())
36       {
37          ref = new WeakReference<Target>(new Target());
38
39          forceGC();
40          
41          assertNull(ref.get());
42       }
43    }
44
45    @Test
46    public void testStrongReferenceKeepsWeakReference()
47    {
48       WeakReference<Target> ref;
49       Target target;
50
51       if (verifyNoPropertyViolation())
52       {
53          target = new Target();
54          ref    = new WeakReference<Target>(target);
55
56          forceGC();
57
58          assertSame(target, ref.get());
59       }
60    }
61
62    /* ClassInfo.refClassInfo wasn't being set to null between JPF runs.  Thus, 
63     * refClassInfo wasn't being updated.  Hence, the WeakReference below would 
64     * be treated as a normal object in GC.  Re-run testGCClearsRef() to 
65     * reproduce the issue.
66     */
67    @Test
68    public void testClearClassInfoRefClassInfo()
69    {
70       testGCClearsRef();
71    }
72    
73    private static void forceGC()
74    {
75       System.gc();         // Mark that GC is needed
76       Verify.breakTransition("testForceGC"); // Cause a state to be captured and hence GC to run
77    }
78    
79    private static class Target   // Make this object easy to find in JPF heap
80    {
81    }
82 }