In one of the puzzle at his blog site, Wouter came up with this java puzzle : Who came first Chicken or Egg. Here is the puzzle from his website:

The egg:

package chicken;  
   
public class Egg {  
    final Object first;  
   
    public Egg(Chicken mom) {  
        first = mom.first;  
    }  
}  


The Chicken:

package chicken;  
   
public class Chicken {  
    final Object first;  
   
    public Chicken(Egg egg) {  
        first = egg.first;  
    }  
   
    public void ask() {  
        // The goal is to reach this line  
        System.out.println("First there was the " + first);  
    }  
}  

The creator:

package creator;  
   
import chicken.Chicken;  
   
public class Creator {  
    public static void main(String[] args) {  
        new Chicken(null).ask();  
    }  
}  

Task is to modify Creator class in a way, that ask method is called. And rule remains that reflection should not be used. [you must run with the security manager enabled (-Djava.security.manager). Your solution must be in the creator package].

Try out before looking for the solution.


Interesting stuff, and below was my solution for the same. Check the use of finalize method for resurrecting the dead object. This is what secured coding standards called “finalizer” attack. Check out here and make sure you write a compliant code.

package creator;  
   
import chicken.Chicken;  
import chicken.Egg;  
   
public class Creator extends Egg {  
    private static Creator badEgg = null;  
   
    Creator(Chicken e) {  
        super(e);  
    }  
   
    public static Creator get() {  
        try {  
            new Creator(null);  
        } catch (Exception ex) {  
            //Who cares. It is expected.  
        }  
        try {  
            synchronized (Creator.class) {  
                while (badEgg == null) {  
                    System.gc();  
                    Creator.class.wait(10);  
                }  
            }  
        } catch (InterruptedException ex) {  
            return null;  
        }  
        return badEgg;  
    }  
   
    public void finalize() {  
        synchronized (Creator.class) {  
            badEgg = this;  
            Creator.class.notify();  
        }  
    }  
   
    public static void main(String[] args) {  
        Creator creator = Creator.get();  
        Chicken goodChicken = new Chicken(creator);  
        goodChicken.ask();  
    }  
}