Skip to main content

Posts

Showing posts from January, 2012

Java puzzler

You'll need an understanding of weak references to have a meaningful stab at this one.


public class Test {

public static void main(String[] args) {
List<byte[]> list = new ArrayList<byte[]>();

Object thing = new Object();
WeakReference<Object> ref = new WeakReference<Object>(thing);

while(ref.get()!=null) {
list.add(new byte[10000]);
}
System.out.println("bam");
}

}


Before reading any further give it a stab, see what you come up with. Then run it and see. Oh and yes, it compiles and runs.






...







Well, there's two possible options that you could have sensibly come up with. The first is what most people assume will always happen - the byte array will fill up to cause an OutOfMemoryError and the weak reference will never be garbage collected because there also exists a strong reference (thing) that remains in scope throughout the application and thus doesn't "let go" of the object. …