Skip to content

Instantly share code, notes, and snippets.

@wbspry
Created August 5, 2014 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wbspry/5c260b84dae3eece125d to your computer and use it in GitHub Desktop.
Save wbspry/5c260b84dae3eece125d to your computer and use it in GitHub Desktop.
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("消えました");
}
}
}
package references;
public class Sheryl {
public void sing(){
System.out.println("生き残りたい");
}
}
まだ生きてます
生き残りたい
GCしました
消えました
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment