Created
April 24, 2018 10:13
-
-
Save hascode/1ae0648a1748d58d08907ec487d24706 to your computer and use it in GitHub Desktop.
Java - WeakReference and WeakHashMap examples
This file contains hidden or 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 net.seibertmedia; | |
import java.util.Map; | |
import java.util.WeakHashMap; | |
import java.util.concurrent.TimeUnit; | |
public class WeakHashmapExample { | |
public static void main(String[] args) throws InterruptedException { | |
Map<Person, String> map = new WeakHashMap<Person, String>(); | |
Person p1 = new Person("Jeff1"); | |
map.put(p1, "String1"); | |
Person p2 = new Person("Jeff2"); | |
map.put(p2, "String2"); | |
Person p3 = new Person("Jeff3"); | |
map.put(p3, "String3"); | |
Person p4 = new Person("Jeff4"); | |
map.put(p4, "String4"); | |
System.out.println("map has " + map.size() + " values"); | |
p2 = null; | |
System.gc(); | |
TimeUnit.SECONDS.sleep(6); | |
System.out.println("map has " + map.size() + " values"); | |
p3 = null; | |
System.gc(); | |
TimeUnit.SECONDS.sleep(6); | |
System.out.println("map has " + map.size() + " values"); | |
} | |
static class Person { | |
private final String name; | |
public Person(final String name) { | |
this.name = name; | |
} | |
@Override | |
public int hashCode() { | |
final int prime = 31; | |
int result = 1; | |
result = prime * result + ((name == null) ? 0 : name.hashCode()); | |
return result; | |
} | |
@Override | |
public boolean equals(Object obj) { | |
if (this == obj) | |
return true; | |
if (obj == null) | |
return false; | |
if (getClass() != obj.getClass()) | |
return false; | |
Person other = (Person) obj; | |
if (name == null) { | |
if (other.name != null) | |
return false; | |
} else if (!name.equals(other.name)) | |
return false; | |
return true; | |
} | |
} | |
} |
This file contains hidden or 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 net.seibertmedia; | |
import java.lang.ref.WeakReference; | |
public class WeakReferenceExample { | |
static class Hard { | |
} | |
public static void main(String[] args) throws InterruptedException { | |
Hard hard = new Hard(); | |
WeakReference<Hard> ref = new WeakReference<>(hard); | |
Runtime.getRuntime().gc(); | |
Thread.sleep(3000); | |
System.out.printf("weak ref is present? %s%n", ref.get() != null); | |
hard = null; | |
Runtime.getRuntime().gc(); | |
Thread.sleep(3000); | |
System.out.printf("weak ref is present? %s%n", ref.get() != null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment