Created
July 7, 2016 17:55
-
-
Save thiagoh/d4b19083d2f793f81b8a8733ad4059db to your computer and use it in GitHub Desktop.
WeakReference example
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.liferay.portal.service; | |
import java.lang.ref.Reference; | |
import java.lang.ref.ReferenceQueue; | |
import java.lang.ref.WeakReference; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class ReferencesTest { | |
private static ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>(); | |
public static void main(String[] args) { | |
new ReferencesTest().doFunction(); | |
} | |
private void doFunction() { | |
Map<Integer, String> map = new HashMap<Integer, String>(); | |
WeakReference<Map<Integer, String>> myMap = new WeakReference<Map<Integer, String>>(map, referenceQueue); | |
map = null; | |
int i = 0; | |
Thread t = new Thread(() -> { | |
while (true) { | |
try { | |
Reference<? extends Object> reference = referenceQueue.remove(1000); | |
if (reference != null) { | |
System.out.println("############## Reference removed!"); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}); | |
t.start(); | |
while (true) { | |
if (myMap != null && myMap.get() != null) { | |
myMap.get().put(i++, "test" + i); | |
System.out.println("im still working!!!!" + Runtime.getRuntime().freeMemory()); | |
} else { | |
System.out.println("*******im free*******"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment