Created
August 5, 2014 07:17
-
-
Save wbspry/5c260b84dae3eece125d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package references; | |
import java.lang.ref.*; | |
public class Main { | |
public static void main(String[] args) { | |
Sheryl strongRef = new Sheryl();//① | |
WeakReference<Sheryl> weakRef = new WeakReference<Sheryl>(strongRef);//② | |
strongRef = null;//③ | |
Sheryl sheryl = weakRef.get(); | |
if (sheryl != null){ | |
System.out.println("まだ生きてます"); | |
sheryl.sing(); | |
}else{ | |
System.out.println("消えました"); | |
} | |
sheryl = null; | |
System.gc();//④ | |
System.out.println("GCしました"); | |
Sheryl sheryl = weakRef.get(); | |
if (sheryl != null){ | |
System.out.println("まだ生きてます"); | |
sheryl.get().sing(); | |
}else{ | |
System.out.println("消えました"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package references; | |
public class Sheryl { | |
public void sing(){ | |
System.out.println("生き残りたい"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
まだ生きてます | |
生き残りたい | |
GCしました | |
消えました |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment