I am keeping a reference to locally created objects in a publicly available map. When i remove the object from map, it should also be removed from memory(nullified).
public class X {
public boolean infiniteloop = true;
public X() {
new Thread(new Runnable() {
@Override
public void run() {
while (infiniteloop) {
System.out.println("Still exists");
}
}
}).start();
}
public class Y{
Map myMap = new HashMap();
public Y() throws InterruptedException{
X x = new X();
myMap.put("Key", x);
Thread.sleep(10000);
((X)myMap.get("Key")).infiniteloop= false;
myMap.remove("Key");
}
}
In the above code, "Still exists" is printend after myMap.remove("Key"). This means the object still exists in memory. How can i remove it from memory?