Friday, May 2, 2008

Singleton across JVM's

When you make an Object singleton, we all know its just unique per jvm or per class loader.

So what if you want to make an object unique in a clustered environment. One way of doing it is using JNDI object binding. Here is some sample code try to run on ur server.

private void jndiObjTest(){

try{
System.out.println("Teting jndi object cache");

NotchClient nc=new NotchClient("Sunny","T");

Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL, "http://localhost:7001");
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.REFERRAL,"throw");
InitialContext ctx = new InitialContext(ht);
ctx.bind("sam_name",nc);

System.out.println("Reading Object from JNDI lookup");
Object o=ctx.lookup("sam_name");

NotchClient n=(NotchClient)o;
System.out.println("Value of obj retrieved from jndi"+n.getName());

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
Note: Please deploy the above code to ur local server to test, standalone java app wont work.

--Sunny

No comments: