Skip to content

Instantly share code, notes, and snippets.

@lukhnos
Created December 9, 2015 17:37
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 lukhnos/f628a45939cba16d3f11 to your computer and use it in GitHub Desktop.
Save lukhnos/f628a45939cba16d3f11 to your computer and use it in GitHub Desktop.
ReferenceQueue leaks demo
/**
* This demonstrates the leaks in ReferenceQueue.
*
* To run the demo, compile the source with:
*
* j2objc ReferenceQueueLeaks.java
* j2objcc ReferenceQueueLeaks.m
*
* Then use the Leaks tool in Instruments and have it run "a.out ReferenceQueueLeaks".
*/
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
import com.google.j2objc.annotations.AutoreleasePool;
public class ReferenceQueueLeaks {
public static void main(String args[]) throws Exception {
for (int i = 0; i < 20; i++) {
System.out.println("testWeakHashMap " + i);
testWeakHashMap();
Thread.sleep(1000);
}
System.out.println("Sleep");
Thread.sleep(30000);
for (int i = 0; i < 20; i++) {
System.out.println("testQueuedWeakReference " + i);
testQueuedWeakReference();
Thread.sleep(1000);
}
System.out.println("Sleep");
Thread.sleep(15000);
System.out.println("End");
}
@AutoreleasePool
public static void testWeakHashMap() {
WeakHashMap<Object, String> m = new WeakHashMap<>();
m.put(new Object(), "some value");
}
public static WeakReference<?> weakRef;
@AutoreleasePool
public static void testQueuedWeakReference() {
final boolean[] dealloced = { false };
ReferenceQueue<? super Object> queue = new ReferenceQueue<Object>();
for (@AutoreleasePool int i = 0; i < 1; i++) {
Object referent = new Object() {
public void finalize() {
dealloced[0] = true;
}
};
weakRef = new WeakReference<Object>(referent, queue);
}
if (weakRef.get() != null) {
throw new AssertionError("Should be null");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment