difference between java.rmi.Naming and java.rmi.registry.LocateRegistry

demonz demonz picture demonz demonz · Nov 30, 2011 · Viewed 9k times · Source

when studying RMI sometimes (head first Java) dudes use

Naming.rebind(name, object) 

but other peoples on the web (oracle) use

Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, object);

I know that hf java is a little old, but i don't see the Naming class deprecated.

So, what's the difference then?

Answer

Gray picture Gray · Nov 30, 2011

[What's the] difference between java.rmi.Naming and java.rmi.registry.LocateRegistry

The difference is that the name field to Naming.rebind() is parsed as an URL while the Registry.rebind() is the "name to associate with the remote reference". The LocateRegistry.getRegistry() call assumes the registry is on the local host at the default port while the Naming.rebind() allows you to specify what registry to use.

Under Java 1.6 Naming.rebind() parses the name as an URL and calls Naming.getRegistry() with the host/port of the registry. That calls LocateRegistry.getRegistry(host, port).

public static void rebind(String name, Remote obj) throws RemoteException, MalformedURLException 
    ParsedNamingURL parsed = parseURL(name);
    Registry registry = getRegistry(parsed);
    if (obj == null)
        throw new NullPointerException("cannot bind to null");
    registry.rebind(parsed.name, obj);
}
...

private static Registry getRegistry(ParsedNamingURL parsed) throws RemoteException {
    return LocateRegistry.getRegistry(parsed.host, parsed.port);
}