I have been reading through the Java tutorial on RMI. I like the approach that is outlined here for implementing a remote interface:
http://download.oracle.com/javase/tutorial/rmi/implementing.html
What I would like to know are 2 things:
1) With regard to the executeTask
method outlined in the aforementioned link, how would this design allow Remote Objects (tasks) access some sort of global state if the ComputeEngine is just calling the execute method of a Task?
2) Would this design be suitable for a multi-threaded environment?
Thanks indeed.
Ad. 1: Please note that remote client does not know anything about ComputeEngine
class, only the Compute
interface. Also, the server implementation might change completely, but if the interface does not change, client shouldn't notice. If you want to pass some context to the task coming from remote client, do it on interface layer:
public class ComputeEngine implements Compute {
private GlobalContext globalContext = //...
public <T> T executeTask(Task<T> t) {
return t.execute(globalContext);
}
This way each task has access to the globalContext
and knows exactly what to expect from globalContext
(what are the server capabilities, the context). GlobalContext
would be a JavaBean or more likely some service interface.
On the client side it might look like this
Compute compute = //obtain RMI client stub somehow
compute.executeTask(new Task<String>() {
public String execute(GlobalContext globalContext) {
//Note that this code is executed on the server and
//getFoo() is implemented on the server side. We only know its interface
globalContext.getFoo();
//...
}
}
Ad. 2: It will work with multiple clients calling the service concurrently. However it is up to you to implement the server in thread-safe manner. The example from tutorial you mentioned in thread-safe, but my code using GlobalContext
might not be. Please notice that several clients will use the same instance of globalContext
concurrently, which might, but does not have to cause some issues. That's probably the most interesting part.
And finally remember that receiving unknown Task
from remote client and running it on server is very impressive, but not quite safe.