samples/gc/test/org/apidesign/gc/CompilerSurprisesTest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 15 Oct 2008 21:39:35 +0200
changeset 281 6befc59fc53c
child 282 b762c8fb572e
permissions -rw-r--r--
Renaming the class and adding code snippet boundaries
     1 package org.apidesign.gc;
     2 
     3 import java.lang.ref.Reference;
     4 import java.lang.ref.WeakReference;
     5 import org.junit.Test;
     6 import org.netbeans.junit.NbTestCase;
     7 import static org.junit.Assert.*;
     8 
     9 // BEGIN: compiler.surprises.intro
    10 public class CompilerSurprisesTest {
    11     Reference<String> cache;
    12 
    13     public String factory() {
    14         String value = new String("Can I disappear?");
    15         cache = new WeakReference<String>(value);
    16         return value;
    17     }
    18 
    19     @Test
    20     public void checkThatTheValueCanDisapper() {
    21         String retValue = factory();
    22         retValue = null;
    23         assertGC("Nobody holds the string value anymore. It can be GCed.", cache);
    24     }
    25 // FINISH: compiler.surprises.intro
    26 
    27 // BEGIN: compiler.surprises.error
    28     @Test
    29     public void obviouslyWithoutClearingTheReferenceItCannotBeGCed() {
    30         String retValue = factory();
    31 // commented out:        retValue = null;
    32         assertNotGC("The reference is still on stack. It cannot be GCed.", cache);
    33     }
    34 // END: compiler.surprises.error
    35 
    36 
    37 // BEGIN: compiler.surprises.surprise
    38     boolean yes = true;
    39     @Test
    40     public void canItBeGCedSurprisingly() {
    41         String retValue;
    42         if (yes) {
    43             retValue = factory();
    44         }
    45         assertGC("Can be GCed, as retValue is not on stack!!!!", cache);
    46     }
    47 // END: compiler.surprises.surprise
    48 
    49 
    50 // BEGIN: compiler.surprises.fix
    51     boolean ok = true;
    52     @Test
    53     public void canItBeGCedIfInitialized() {
    54         String retValue = null;
    55         if (ok) {
    56             retValue = factory();
    57         }
    58         assertNotGC("Cannot be GCed as retValue is not stack", cache);
    59     }
    60 // END: compiler.surprises.fix
    61 
    62     private static void assertGC(String msg, Reference<?> ref) {
    63         NbTestCase.assertGC(msg, ref);
    64     }
    65 
    66     private static void assertNotGC(String msg, Reference<?> ref) {
    67         try {
    68             NbTestCase.assertGC("Cannot be GCed. " + msg, ref);
    69         } catch (Error ex) {
    70             // OK
    71             return;
    72         }
    73         fail(msg + ref.get());
    74     }
    75 }