Google

Monday, January 31, 2005

When to use PortableRemoteObject.narrow() and when to simply cast the reference?

Most RPC protocols other than RMI can't take adventage of Java's code loading facilities (because they were not designed to work solely with Java). IIOP falls into this category. Therefore, when an IIOP stub is passed to a caller as a placeholder for a remote object, the IIOP protocol dictates that the actual returned proxy will be of the declared return type, not the actual run-time type of the returned object. This is because the receiving system is only guaranteed to know the declared return type and cannot generally load remote code.
So, the actual stub you get in an RMI-IIOP call has the declared type, not the run-time type (more accurately, it is only guaranteed to be as specific as the declared type). So a normal Java cast will not work.

PortableRemoteObject.narrow() is a way to support type narrowing in such protocols. It explicitly requests to load the stub with the specified type (which may involve contacting the server to verify that the requested stub type is supported by the referenced object).

So, to answer your question, you should use narrow() whenever you make a remote call whose declared return value is not what you want. A common example of this is when you do a JNDI lookup for a remote object (which could translate into an IIOP call to a CosNaming service). You should also use narrow() when the type declaration is implicit, such as when using a Collection returned from an entity finder method.
In other, non-remote cases (such as EntityContext.getEJBObject()) you can usually assume a normal cast is sufficient. There is usually no reason that stops the container from implementing this efficiently, so the EJB spec requires that containers take care of the narrowing for you.