THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

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 taking 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 executing tasks for different
clients. ComputeServerImpl extends UnicastRemoteObject, 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 (implicitly invoked) UnicastRemoteObject
constructor when it registers the object with the RMI system.


Now comes the fun part. Clients can ask the server to perform any computation at all. Suppose, for example,
that you want to compute π to some number of decimal places. You can have the compute server do this for
you:


import java.math.BigDecimal;


public class Pi implements Task {
private int decimals;


/* Calculate Pi to a given number of decimal places /
public Pi(int decimals) {
this.decimals = decimals;
}


public Object run() {
BigDecimal res = computePi();
return res;
}


BigDecimal computePi() {
// ...
}
}


The Pi class implements the Task interface with a run method that returns a java.math.BigDecimal
object containing the computed result. You then put the compiled Pi class someplace where it can be
downloaded from a URL, just as an applet class would be. The URL from which to download the code will be
set as a property for your client.


When you invoke the compute server's compute method, passing a Pi object, the server will need the Pi
class. It will look at the URL that has been implicitly passed with the request, download the class, and run it in
a secure sandbox. It will then invoke the Pi object's run method and return the result.


This ComputeServer example leverages the Java virtual machine's homogeneous computing model, in
which all code means the same thing on all platforms, and its security model, in which downloaded code can

Free download pdf