Skip to content

Instantly share code, notes, and snippets.

@smanek
Created April 30, 2011 23:54
Show Gist options
  • Save smanek/950110 to your computer and use it in GitHub Desktop.
Save smanek/950110 to your computer and use it in GitHub Desktop.
import com.google.common.collect.Lists;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.List;
public class SoftReferenceTest {
private static final boolean KEEP_SOFT_REF = false;
public static void main(String[] args) {
final ReferenceQueue<byte[]> referenceQueue = new ReferenceQueue<byte[]>();
int polled = 0;
List<SoftReference<byte[]>> refs = Lists.newLinkedList();
List<byte[]> hard = Lists.newLinkedList();
for (int i = 0; i < 100; i++) {
byte[] bigThing = new byte[1000000];
SoftReference<byte[]> sr = new SoftReference<byte[]>(bigThing, referenceQueue);
hard.add(bigThing);
if (i > 2) {
hard.remove(0);
}
if (KEEP_SOFT_REF) {
refs.add(sr);
}
while (referenceQueue.poll() != null) {
polled++;
System.out.println("polled " + polled + " with i = " + i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment