Search code examples
javarminaming

What is the difference between java.rmi.Naming and java.rmi.registry.LocateRegistry


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?


Solution

  • [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);
    }