Java Reference
In-Depth Information
public Object compute(Task task) {
return task.run();
}
public static void main(String[] args)
throws java.io.IOException
{
// use the default, restrictive security manager
System.setSecurityManager(new RMISecurityManager());
ComputeServer server = new ComputeServerImpl();
Naming.rebind("ComputeServer", server);
System.out.println("Ready to receive tasks");
}
}
This code is also straightforward. When a
compute
invocation arrives from
a client,
ComputeServerImpl
implements the
ComputeServer
interface by tak-
ing the
Task
object it is given and invoking its
run
method, returning the
resulting
Object
. Each incoming request typically gets its own thread, so
this compute server implementation could have many concurrently ex-
ecuting tasks for different clients.
ComputeServerImpl
extends
UnicastRe-
moteObject
, which provides references for single-server remote method
invocation.
UnicastRemoteObject
, like most types needed only by servers,
is defined in
java.rmi.server
. The
ComputeServerImpl
constructor declares
that it throws
RemoteException
because it can be thrown by the (impli-
citly invoked)
UnicastRemoteObject
constructor when it registers the ob-
ject with the
RMI
system.
Now comes the fun part. Clients can ask the server to perform any com-
putation at all. Suppose, for example, that you want to compute
p
to
some number of decimal places. You can have the compute server do
this for you: