Cool Penguin

Simple developer guides

Java

More

on CoolPenguin.net:

How to speed up EJB lookups

J2EE applications usually invoke the same EJBs several times. EJB lookups are expensive, a possible way to reduce that overhead is to cache the bean home. There are many ways to do that, the following example is not the best but maybe the simplest: uses the singleton design pattern.

import javax.naming.NamingException;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class MyBeanHomeCache {

    private static MyBeanHome home = null;

    public static MyBeanHome getHome() throws NamingException {
        try {
            if (home == null) {
                InitialContext context = new InitialContext();
                home = (MyBeanHome) PortableRemoteObject.narrow(
                        context.lookup("test.myBean"),
                        MyBeanHome.class);
            }
            return home;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}