Last active
September 2, 2016 20:51
-
-
Save runnerdave/338036c1a0685ba7827f34c07ab7fcea 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 com.example.reference; | |
import java.lang.ref.PhantomReference; | |
import java.lang.ref.ReferenceQueue; | |
import java.lang.ref.SoftReference; | |
import java.lang.ref.WeakReference; | |
/* | |
* https://dzone.com/articles/java-different-types-of-references | |
*/ | |
public class ReferenceExample { | |
private String status ="Hi I am active"; | |
public static void main(String[] args) { | |
ReferenceExample ex = new ReferenceExample(); | |
ex.strongReference(); | |
ex.softReference(); | |
ex.weakReference(); | |
try { | |
ex.phantomReference(); | |
} catch (InterruptedException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
} | |
public String getStatus() { | |
return status; | |
} | |
public void setStatus(String status) { | |
this.status = status; | |
} | |
@Override | |
public String toString() { | |
return "ReferenceExample [status=" + status + "]"; | |
} | |
public void strongReference() | |
{ | |
ReferenceExample ex = new ReferenceExample(); | |
System.out.println(ex); | |
} | |
public void softReference() | |
{ | |
SoftReference<ReferenceExample> ex = new SoftReference<ReferenceExample>(getRefrence()); | |
System.out.println("Soft refrence :: " + ex.get()); | |
} | |
public void weakReference() | |
{ | |
int counter=0; | |
WeakReference<ReferenceExample> ex = new WeakReference<ReferenceExample>(getRefrence()); | |
while(ex.get()!=null) | |
{ | |
counter++; | |
System.gc(); | |
System.out.println("Weak reference deleted after:: " + counter + ex.get()); | |
} | |
} | |
public void phantomReference() throws InterruptedException | |
{ | |
final ReferenceQueue queue = new ReferenceQueue(); | |
PhantomReference<ReferenceExample> ex = new PhantomReference<ReferenceExample>(getRefrence(),queue); | |
System.gc(); | |
queue.remove(); | |
System.out.println("Phantom reference deleted after"); | |
} | |
private ReferenceExample getRefrence() | |
{ | |
return new ReferenceExample(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment