Professional Documents
Culture Documents
SL-370
Student Guide
Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.
Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark
in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.
Sun, Sun Microsystems, the Sun Logo, Jini, Java, JavaSpaces, JDK, 100% Pure Java, and JavaBeans are trademarks or registered trademarks
of Sun Microsystems, Inc. in the U.S. and other countries.
The OPEN LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges
the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry.
Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun’s licensees who imple-
ment OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements.
RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g) (2)(6/87) and
FAR 52.227-19(6/87), or DFAR 252.227-7015 (b)(6/95) and DFAR 227.7202-3(a).
DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRAN-
TIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-IN-
FRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Please
Recycle
Contents
About This Course..................................................................................... vii
Course Goal ..........................................................................................vii
Course Overview ............................................................................. viii
Course Map.......................................................................................... ix
Module-by-Module Overview ........................................................... x
Course Objectives............................................................................... xii
Skills Gained by Module................................................................. xiii
Guidelines for Module Pacing ........................................................ xiv
Topics Not Covered........................................................................... xv
How Prepared Are You?.................................................................. xvi
Introductions .................................................................................. xviii
How to Use Course Materials ......................................................... xix
Course Icons and Typographical Conventions ............................ xxi
Icons ............................................................................................xxi
Typographical Conventions ...................................................xxii
Acronyms ........................................................................................ xxiv
Introduction to Jini Technology..............................................................1-1
Objectives ............................................................................................1-1
Relevance............................................................................................ 1-2
The Vision Behind Jini Technology ................................................ 1-3
Virtual Demonstration ..................................................................... 1-5
What Is Happening on the Plane? .................................................. 1-6
More About Services ........................................................................ 1-8
Distributed Computing Requirements ........................................ 1-10
Distributed Computing Concepts ................................................ 1-11
Moving Code ................................................................................... 1-12
How Code Moves ........................................................................... 1-13
Discussion: Applications of Jini Technology .............................. 1-14
Check Your Progress ...................................................................... 1-15
Think Beyond .................................................................................. 1-16
Essentials of the RMI System ..................................................................2-1
Objectives ............................................................................................2-1
i
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Relevance............................................................................................ 2-2
Introducing RMI................................................................................ 2-3
How an RMI Call Works.................................................................. 2-5
How RMI Works ............................................................................... 2-7
Another Perspective ......................................................................... 2-9
Two RMI Programming Models................................................... 2-10
A Minimal RMI Example ............................................................... 2-12
A Minimal RMI Example – The Interface.................................... 2-13
A Minimal RMI Example – The Server........................................ 2-14
A Minimal RMI Example – The Client......................................... 2-16
A Minimal RMI Example – Executing ......................................... 2-17
Downloading the Stub ................................................................... 2-18
Downloading the Stub – The Client ............................................. 2-20
Downloading the Stub – The Policy File ..................................... 2-21
Downloading the Stub – Executing.............................................. 2-22
Agent Example – The Interface..................................................... 2-26
Agent Example – The Server ......................................................... 2-27
Agent Example – The Agents........................................................ 2-28
Agent Example – Agent Client ..................................................... 2-30
Agent Example – Deployment Architecture............................... 2-31
Agent Example – Starting the Server ........................................... 2-33
Agent Example – Running the Client .......................................... 2-35
Exercise: Deploying A Distributed RMI System ........................ 2-36
Preparation...............................................................................2-36
Tasks .........................................................................................2-36
Exercise Summary...................................................................2-37
Check Your Progress ...................................................................... 2-38
Think Beyond .................................................................................. 2-39
Investigating Jini Technology .................................................................3-1
Objectives ............................................................................................3-1
Relevance............................................................................................ 3-2
What Is Jini Technology? ................................................................. 3-3
Example Services............................................................................... 3-5
Supporting Jini Technology............................................................. 3-7
Components of Jini Technology...................................................... 3-9
Jini Programming Model ............................................................... 3-11
Programming Model Assumption ............................................... 3-13
Leasing Overview ........................................................................... 3-15
Distributed Events Overview........................................................ 3-17
Jini Technology Transactions ........................................................ 3-19
Overview of Lookup and Discovery Protocols .......................... 3-21
Overview of JavaSpaces Technology ........................................... 3-23
Running the Distribution Software .............................................. 3-25
Running the Services Browser ...................................................... 3-29
Exercise: Running the Jini Services and Browser ....................... 3-34
iii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Lookup and Discovery ..............................................................................6-1
Objectives ............................................................................................6-1
Relevance............................................................................................ 6-2
Roles of the Lookup and Discovery Protocols.............................. 6-3
Discovery Protocol Software Requirements ................................. 6-5
Discovery Protocol Network Requirements ................................. 6-6
Unicast Discovery Protocol ............................................................. 6-8
Multicast Protocols ......................................................................... 6-10
Looking Up a Service...................................................................... 6-12
Example One: The LookupLocator Class................................... 6-13
Using a ServiceRegistrar Object ............................................. 6-14
The ServiceRegistrar Support Classes ................................... 6-15
What Is an Entry Object? .............................................................. 6-17
Example of Static Lookup .............................................................. 6-19
Dynamic Location of Lookup Services ........................................ 6-21
Example: The LookupLocatorDiscovery Class ....................... 6-22
Example: The LookupDiscovery Class....................................... 6-25
Dynamic Service Information ....................................................... 6-27
Service Notification Request Example......................................... 6-29
Registering Services ........................................................................ 6-30
ServiceRegistrar Support Classes ........................................... 6-31
The JoinManager Class ................................................................. 6-35
Implementing a Service.................................................................. 6-37
Attributes for Services .................................................................... 6-38
Example Service .............................................................................. 6-40
Using the JoinManager Class....................................................... 6-42
Non-Core Classes............................................................................ 6-47
Exercises: Using Lookup Services ................................................ 6-49
Preparation...............................................................................6-49
Tasks .........................................................................................6-49
Exercise Summary...................................................................6-50
Check Your Progress ...................................................................... 6-51
Think Beyond .................................................................................. 6-52
Putting it Together.....................................................................................7-1
Objectives ............................................................................................7-1
Relevance............................................................................................ 7-2
Example of Putting it Together ....................................................... 7-3
The MapAll Class ......................................................................7-9
Investigating the Code for the MapAll Classes ....................7-9
The Browse Class ............................................................................ 7-12
Running the Examples ................................................................... 7-16
Exercise: Investigating Service Proxy-to-Service
Communication............................................................................ 7-18
Preparation...............................................................................7-18
Tasks .........................................................................................7-18
v
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Enabling Class Loading .................................................................. A-3
Enabling Object Loading................................................................. A-4
Service Requirements ...................................................................... A-6
Attribute and Entry Requirements............................................... A-8
Multicast Issues ................................................................................ A-9
Check Your Progress ..................................................................... A-10
Course Goal
On completion of this course you should understand the significance
of Jini™ technology, and use Jini technology to design and implement
solutions to real world problems.
vii
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Course Overview
The following course map enables you to see what you have
accomplished and where you are going in reference to the course goal:
Leases Distributed
Events
Jini Transactions
JavaSpaces
Technology
The skills for Programming Distributed Services With Jini Technology are
shown in column 1 of the following matrix. The black boxes indicate
the main coverage for a topic; the gray boxes indicate the topic is
briefly discussed.
Module
Skills Gained 1 2 3 4 5 6 7 8 9
This course does not cover the topics shown on the above overhead.
Many of the topics listed on the overhead are covered in other courses
offered by Sun Educational Services:
This course covers both the principles and concepts of Jini technology,
and the practicalities of programming with it. You will be introduced
to the main classes and interfaces of Jini technology, and shown code
examples demonstrating the major functionalities of Jini technology.
Now that you have been introduced to the course, introduce yourself
to each other and the instructor, addressing the items shown on the
above overhead.
Icons
Additional resources – Indicates additional reference materials are
available.
Exercise objective – Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.
Courier bold is used for characters and numbers that you type. For
example:
system% su
Password:
It is also used for each code line that will be referenced in text.
For example:
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:
On Solaris
cd server_root/bin
On Microsoft Windows
cd server_root\bin
Objectives
Upon completion of this module, you should be able to:
1-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
Relevance
Virtual Demonstration
For the most part, the most advanced distributed computing protocols,
even when combined with application-specific protocols designed to
address particular problems, still have some significant limitations. In
these systems, although the data format, message format, formats for
passing requests, parameters, and results, have all been standardized,
the executable code that runs on distributed machines is usually
specific to the hardware architecture of the machine on which it runs.
Because of this, you cannot easily move code between systems.
If code can run only on the system it was initially installed on, a
number of limitations are placed on the overall architecture of a
software system running in this type of environment. However, if you
can move code around: you can use any system with spare computing
power to execute any job as needed; if a system fails, for whatever
reason, any other system in the network can take over the failed
system’s work; and any desktop machine can run your favorite
application programs.
Moving Code
Because code can move easily from one machine to another, and it is
common for a system to run code on behalf of a third party that might
be only partially trusted, the Java virtual machine (JVM) and the Java
programming language were designed from the start to implement
effective and useful security constraints. These constraints enable the
owner of one system to protect that system against unauthorized
access or tampering by third parties. Third-party code is executed
provided it does not attempt to do anything unauthorized.
You can load the class file data from anything that can supply a
sequence of bytes. Obvious examples include disk files, and network
uniform resource locators (URLs). In fact, the network URL
mechanism is so flexible, (especially given the possibility of defining a
new protocol to be used in a URL), that a URL can describe any likely
class source. The applet-loading mechanism used when running
applets in Web pages progresses in this manner.
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
How well do you know the Remote Method Invocation (RMI)? Have
you, or any of your colleagues had any difficulties when deploying a
distributed system using this technology?
Objectives
Upon completion of this module, you should be able to:
● Write and deploy RMI systems that have stubs on the client
systems
● Write and deploy RMI systems that do not have stubs on the client
systems
2-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Relevance
Introducing RMI
● When the call is made, the invoking system must describe which
method is to be invoked and the object on which the invocation is
to occur.
● After the method has completed, any return value must be passed
back to the invoking virtual machine.
For these three items to work, there must be a protocol that states how
a method call request is to be described, and another protocol that
describes how method arguments and return values are transported
Another Perspective
There are two distinct ways of programming with the RMI system. In
what might be called the conventional approach, classes are not
moved between systems; all that happens is the remote method is
invoked on the server by a client. Argument values are passed from
the client to the server and the return value is passed from the server
to the client. In many ways, this differs only slightly from an
automated remote login mechanism. The behavior that is invoked by
the client is predefined on the server, and the format of arguments and
return values is fixed. This is a powerful and valuable mechanism.
However, there is another way to use RMI that is considerably more
flexible.
In the agent model, one or more objects move between systems. These
objects define both state and behavior. That is, not only do they carry
data from one system to another, through the power of class
downloading, they also carry with them code that is to be executed.
Using this model, you can use some arbitrary system to execute the
code, allowing the code to run wherever is most appropriate at the
time. You can decide where to run the code on any basis; for example,
mathematically intense computation might be performed on a large
system with a powerful central processing unit (CPU). You can
allocate other less demanding tasks to the system with the lightest
load at the time.
Using the agent object, the object that is moving between systems
carries not only argument data but also results. Once a computation
has been performed, the agent object can return to, or be fetched by,
the original client system, or be passed to other systems in the
network.
The remote service accepts a text string, and returns another text
string. The service is accessed by a remote method called tellMe. The
pages that follow describe the individual aspects of the example
system and how to run it.
The client invokes the server using the argument to its own command
line as the question, while the server replies using the argument to its
own command line. This simple approach ensures that no significant
computation is required in the remote method, and therefore, no
complex but irrelevant algorithm is introduced.
1
2 public interface TellMeServer extends Remote {
3 public String tellMe(String question) throws RemoteException;
4 }
Code 2-2 TellMeServer.java
1 import java.rmi.*;
2 import java.rmi.server.*;
3
4 public class RMIServer
5 extends UnicastRemoteObject
6 implements TellMeServer {
7
8 private String message;
9
10 public RMIServer(String message) throws RemoteException {
11 this.message = message;
12 }
13
14 public String tellMe(String question) {
15 System.out.println("Someone asked " + question + "\n");
16 return "The answer to " + question +
17 " is " + message + "\n";
18 }
19
20 public static void main(String args[]) throws Throwable {
21 RMIServer ss = new RMIServer(args[0]);
22 Naming.rebind("TellMe", ss);
23 }
24 }
Code 2-3 RMIServer.java
In this example, the remote object is created in the main method, and
is registered with the standard rmiregistry using the method call
Naming.rebind on line 22.
1 import java.rmi.*;
2
3 public class RMIClient {
4 public static void main(String args[]) throws Throwable {
5 String question = args[0];
6 TellMeServer tms =
7 (TellMeServer)Naming.lookup("rmi://localhost/TellMe");
8 String answer = tms.tellMe(question);
9 System.out.println("Answer:\n" + answer);
10 }
11 }
Code 2-4 RMIClient.java
The client must first obtain a reference to the remote object. This
remote reference is an instance of the stub class, and can be obtained
from the rmiregistry using the Naming.lookup call. This is simply a
convenient, conventional way to obtain a stub. You can also pass these
objects around under program control; however, this is beyond the
scope of this section.
In its simplest form, you can run this example by starting the
rmiregistry, server, and client from the same directory. In this
situation, all class files are available to all three virtual machines. This,
while a rather limited use of RMI, is a useful way to demonstrate the
basic operation.
Compile all the classes, and create the stub definition class. These
operations use the javac and rmic commands.
Start the server next, using the java command and providing the
name of the server startup class RMIServer and the answer string that
it is to send when it receives a query. If you want to provide a multi-
word string, you must use quotes around it; otherwise, it is treated as
multiple arguments of one word each.
Start the client, providing it with the question to ask. You might need
to use quotes here as well.
One of the most significant, and unique, features of RMI is the ability
to download code as needed. The most basic situation in which this
need can arise is when a client needs access to the server, but does not
have the stub installed. In fact, this arrangement is considered the
normal situation. In the downloadable stub scenario, nothing in the
code of the client or server must change, but the client must be
running with an installed security manager. This requirement is a
protection against the potential for attack that arises if a system is
willing to download code, but has not taken the trouble to install a
security policy.
1 import java.rmi.*;
2
3 public class RMIClient {
4 public static void main(String args[]) throws Throwable {
5 //System.setSecurityManager(new SecurityManager());
6 String question = args[0];
7 Server server =
(Server)Naming.lookup("rmi://" + args[1] + "/Server");
8 String answer = server.tellMe(question);
9 System.out.println("Answer:\n" + answer);
10 }
11 }
Code 2-5 RMIClient.java Version for Downloading Stub
This code example shows the client again. However, there are two
changes. First, there is a commented out line (line 5) that shows how
you could install the security manager programmatically. This is not
needed because the example assumes that you will invoke the
command line option to install the security manager.
The second change is that the name used to look up the service has
been changed. In the previous example, the service was taken to be
located on the same system as the client. In this case, that is not
necessarily the case and so it is necessary to explicitly state what
system hosts the required service. To do this, use the longer form of
the lookup string rmi://serverhostname/servicename. You can
add a port number to this specification if a nonstandard port has been
used for the registry. Such a specification would look like the
following: rmi://serverhostname:portnum/servicename.
1 grant {
2 permission java.security.AllPermission;
3 };
Code 2-6 Permission File
Because you have installed the security manager, you must run this
example using a policy file. This is needed because the default
behavior of the security manager is to refuse all requests made by
classes that are not part of the original Java technology platform
distribution. This means that your program classes, and also the stub
that is to be downloaded, would be denied access to files and the
network. Clearly these classes cannot operate properly under such
complete restrictions.
The policy file shown here grants all permissions to all classes,
regardless of from where they are loaded. This is convenient in a
development environment, because it allows you to defer security
configuration until you have a working program. However, it is
inappropriate for a delivered system.
In the next step, you need to ensure that the stub file is not available to
the registry or client. The client should have access to the client class
(RMIClient.class), the interface definition (Server.class), and the
policy file. However, the server should have all the classes available
locally. You must also ensure that you have placed the stub class in a
directory that will be published by a web server, and that web server is
running.
Start the server and provide the following command line argument:
-Djava.rmi.server.codebase=xxx
substituting the URL from which the stub can be loaded in place of
xxx. Ensure that the URL you specify is explicit enough to be
meaningful in the context of both the registry and the client.
Finally, start the client. In this case, you must ensure that the security
manager is installed, and that an appropriate policy file is specified.
Without the security manager, the RMI system cannot load the stub
class, and without an appropriate policy, RMI cannot make the
network connection.
1 import java.rmi.*;
2
3 public interface AgentRunner extends Remote {
4 public Runnable execute(Runnable r) throws RemoteException;
5 }
Code 2-7 AgentRunner.java
In the agent example, the idea is that the client sends code to the
server for execution. The server has not seen this code before, and the
classes are not available to the server locally. In this case, the server
must load classes made available by the client. In addition, there must
be a prior agreement about the nature of the job that the client will
send to the server.
To describe how code is run without specifying what the code is, you
can use an interface definition. In this example, the interface Runnable
is used to describe the job. This indicates that the job has a method
public void run() that is to be used to execute the work.
1 import java.rmi.*;
2 import java.rmi.server.*;
3
4 public class AgentServer
5 extends UnicastRemoteObject
6 implements AgentRunner {
7
8 public AgentServer() throws RemoteException {
9 }
10
11 public Runnable execute(Runnable r) {
12 r.run();
13 return r;
14 }
15
16 public static void main(String args[]) throws Throwable {
17 AgentServer server = new AgentServer();
18 Naming.rebind("AgentServer", server);
19 }
20 }
Code 2-8 AgentServer.java
The example agents all perform simple tasks. The results of any
operations are stored in the agents themselves. The agents must
implement both the Serializable and Runnable interfaces. The
Runnable interface is required to make the object a legal argument to
the remote execute method, while the Serializable flag is needed to
allow the agent to be passed as an argument to any remote method.
Serialization is used to transmit the argument and return values.
1 import java.io.*;
2
3 public class RunnableOne implements Runnable, Serializable {
4 private int runCount;
5
6 public void run() {
7 System.out.println("Hello, I’m a "RunnableOne"");
8 runCount++;
9 }
10
11 public String toString() {
12 return "I’m a "RunnableOne" that’s run " +
13 runCount + " times";
14 }
15 }
Code 2-9 RunnableOne.java
1 import java.io.*;
2
3 public class RunnableTwo implements Runnable, Serializable {
4 public void run() {
5 System.out.println(toString());
6 }
7
8 public String toString() {
9 return "Hello, I’m a "RunnableTwo"";
10 }
11 }
Code 2-10 RunnableTwo.java
1 import java.io.*;
2
1 import java.rmi.*;
2 import java.net.*;
3
4 public class AgentClient {
5 public static void main(String args[]) throws Throwable {
6 AgentRunner server = (AgentRunner)Naming.lookup(args[0]);
7
8 URL [] classSources = { new URL(args[1]) };
9 ClassLoader cl = new URLClassLoader(classSources);
10 Runnable r = (Runnable)cl.loadClass(args[2]).newInstance();
11
12 r = server.execute(r);
13 System.out.println("Returned runnable is: " + r);
14 }
15 }
Code 2-12 AgentClient.java
This technique is not better than using the codebase specification, but
it might be useful, particularly if classes must be available on a variety
of different web servers. In general, the major advantages of using the
standard codebase mechanism are a) it is standard and b) it is faster.
When the agent example is set up, the server should have direct access
to the classes for the server itself, the interface that defines its own
remote interface, and its own stub. In addition, there should be a
policy file applied to the server, because the server is expected to load
the agent classes from remote locations. This is permitted only if you
have installed a security manager; therefore, you must have a policy
file in place.
When the client executes the Naming.lookup call on the registry, the
response is a copy of the stub instance (Step 3). For this to be
deserialized at the client, the class is required. This is loaded from the
server’s webserver in Step 4.
In Step 5, the client loads the agent code from another web server,
using the URL specified on its command line. An instance of the agent
is created and sent across to the server as the argument to the execute
call (Step 6). Before this can be deserialized, just as for the stub, the
classfile must be loaded. This is done in Step 7.
Once the agent has been deserialized in the server, its run method is
executed and the resulting, probably modified, agent is serialized
again and sent back to the client (Step 8). Because the client already
has the defining class, this does not need to be reloaded.
Before starting the RMI server, the webserver that provides remote
access to the RMI server’s stub class must be running. If this is not
done, then the registry cannot load the stub, and the Naming.rebind
call in the rmi server will fail. Start the webserver and ensure that the
Once rmiregistry and the webserver are running, you should start
the RMI server. You must use a security manager and policy;
otherwise, the RMI server cannot load the agent classes from the
clients. In addition, you must specify the correct URL at which you can
load the server’s stub class. This is done using the
java.rmi.server.codebase property.
The client must load the stub class over the network; therefore, it must
be started with a security manager and policy file. Three command
line arguments are required. The first of these is the RMI URL that is
used to locate the agent servers’ stub in the rmiregistry. The second
is the base URL from which the agent classes are to be loaded. Finally,
the class name of the agent. If the agent class is a member of a
package, you should include this in the class name specification.
Preparation
Examine the code for the agent example shown in the course notes.
Review the descriptions of how it should be deployed and run.
Tasks
Refer to the file README in the directory mod02.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ Write and deploy RMI systems that have stubs on the client
systems
❑ Write and deploy RMI systems that do not have stubs on the client
systems
Objectives
Upon completion of this module, you should be able to:
● List the four key features of the Jini programming model and give
an overview of each feature
● Start the services that are supplied with the Jini technology
distribution, the JavaSpaces service, and run the demonstration
browser provided with the Jini technology distribution
3-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Relevance
Now that you have looked at the capabilities of RMI, the additional
features Jini technology offers will be examined. Jini technology is
described as "software to federate groups of services."
Before this description is helpful, you must know what a service is. A
service can provide any functionality that is accessible over the
network. This might be a server in the traditional sense, where one
system accepts remote requests and processes them to produce results.
It might be a class that gets downloaded and executed on the client. Or
it might be some combination of the two, so that part of the service is
loaded into the client, and that part connects with a server system
elsewhere.
In all cases, some code is loaded into the client, although this code
might only be the RMI stub that connects to the server host.
Regardless of the nature of the service, that part of the service that is
loaded into clients is referred to as the "service proxy."
Example Services
The interface specification should include only those methods that are
core to the service. If you have secondary capability, you should define
multiple interfaces, so that a fully featured service implements all
interfaces, but a more limited one implements only a small number of
the core interfaces.
Jini technology is 100% Pure Java™, which means that it can build on
the capabilities of the RMI system, and inherits the fundamental
security of the Java virtual machine and its libraries. In the future, Jini
technology will provide additional security mechanisms built on the
foundation of Java security. These security mechanisms will facilitate
the construction of distributed security environments.
To run Jini software, you must have a Java 1.2 virtual machine; that is,
either the Java Development Kit (JDK™) Version 1.2 or JRE 1.2, which
forms part of the Java 2 technology platform. This revision of virtual
machine is required because Jini technology software is dependent on
certain enhancements to the RMI system that were introduced at this
level.
● Services
Each of these three parts of Jini technology are built, to some extent, in
terms of the others. Because of this, your understanding of each will
improve as you understand the others.
● Leases
● Distributed events
● Transactions
The next few pages present an outline of these features and later in
this course, an entire module is dedicated to each feature.
Leasing Overview
JDK 1.1 introduced events into the core Java technology APIs. Events
are highly efficient, loosely coupled, and easy to understand
mechanisms for asynchronous communication between separate parts
of a system. Unfortunately, there are two problems with using the
standard event mechanism defined by JDK 1.1 in a distributed
environment.
The first problem is that all RMI remote method calls must be declared
so that they can throw a RemoteException. However, the definition of
the basic event listeners in JDK 1.1 preclude this. Therefore, you must
declare the distributed event listener method as potentially throwing a
RemoteException.
You can summarize this information as follows: JDK 1.1 events do not
support unreliable networks.
Jini Lookup and Discovery protocols are used to locate Jini Technology
Lookup services and find entries within them.
The read operation attempts to return a copy of a data item from the
space. You supply a template, which is an incomplete version of the
object you are looking for, and if an object exists within the space that
matches the non-null parts of the template, a copy of that object is
returned.
The services that are new in Jini technology are the Lookup and
Transaction services.
The final service you will commonly run is the JavaSpaces service.
This, while not formally part of Jini technology, is closely related, and
finds a place in many Jini technology-based systems.
This script starts all the software in the Jini technology distribution,
and also the JavaSpaces software. It is a Korn shell script intended for
use in a Unix® environment; however, you can translate this into a
batch file for Microsoft Windows environments. The first part of the
script defines a number of variables that are used later in the script.
1 #!/usr/bin/ksh
2
3 JINI_BASE=/home/simonr/jini1_0
4 LOOKUP_POLICY=${JINI_BASE}/example/lookup/policy.all
5 TXN_POLICY=${JINI_BASE}/example/txn/policy.all
6 SPACE_POLICY=${JINI_BASE}/example/books/policy.all
7 WEB_HOST=$(hostname)
8 WEB_PORT=8080
9 RMID_LOG=./log
10 LOOKUP_LOG=/tmp/reggie.log
11 LOOKUP_GROUPS=public
12 TXN_GROUP=public
13 TXN_LOG=/tmp/txn_log
14 SPACE_GROUP=public
15
16 java -jar ${JINI_BASE}/lib/tools.jar -port $WEB_PORT -dir
${JINI_BASE}/lib &
17
18 rm -rf ${LOOKUP_LOG} ${TXN_LOG} ${RMID_LOG}
19 rmid &
20
21 sleep 10
22
23 java -jar ${JINI_BASE}/lib/reggie.jar \
24 http://${WEB_HOST}:${WEB_PORT}/reggie-dl.jar \
25 ${LOOKUP_POLICY} ${LOOKUP_LOG} ${LOOKUP_GROUPS} &
26
27 java -jar \
28 -Djava.security.policy=${TXN_POLICY} \
29 ${JINI_BASE}/lib/mahalo.jar \
30 http://${WEB_HOST}:${WEB_PORT}/mahalo-dl.jar \
31 ${TXN_POLICY} ${TXN_LOG} ${TXN_GROUP} &
32
33 java -jar \
34 -Djava.security.policy=${SPACE_POLICY} \
35 -Djava.rmi.server.codebase=http://${WEB_HOST}:${WEB_PORT}/outrigger-
dl.jar \
The web server is provided inside the file tools.jar in the lib
directory of the distribution. The jarfile’s information section contains
the tag "Main-Class:" that allows it to be run directly using the Java
Extension Framework mechanism. In addition to starting the server,
you can specify the TCP port number and base address using
command line arguments.
Starting the rmid process is easy; simply issue the command, rmid.
The rmid command starts, and restarts as necessary, long-term RMI
services. While this concept is valuable in a production environment, it
can be inconvenient in a development situation. Specifically, if you kill
a Jini technology service and try to restart it using an updated class,
you can run into trouble because the rmid program has restarted and
recovered the old version of the service. In a development situation,
you should delete the entire contents of the log directory each time
you are about to start the rmid program. In this way, rmid will start up
without restarting any previously run services.
All three of the main services are packaged into jar files in the same
way as the web server. Because of this, they are all started using java
-jar type commands. The following paragraphs describe the
argument lists.
Running the browser takes a different format again from those seen in
the other services. The browser is not packaged as an executable jar
file, but must be launched by adding the jar to the classpath, and then
running the class com.sun.jini.example.browser.Browser. The
java.rmi.server.codebase property and the policy file are both
specified in the conventional way, using command line properties.
In the text field, type the name of the host running the Lookup service
you want. If the service is running on a nonstandard port, you can
indicate this by adding the port number separated by a full colon ":".
Once a registrar has been recognized, you can select it from the list
that is displayed beneath the Registrar menu item. When a Lookup
service has been selected, the display changes to show the number of
services registered in that Lookup service. This number includes the
Lookup service itself. Selecting the Services menu item shows a list of
the classes that are registered as services. Depending upon the
configuration of the browser under the Options menu item, this list
might list the main class of each service, or might include the parent
classes in the hierarchy.
Preparation
Review the descriptions in the course notes that describe how to run
the services. Locate the distribution in your student directory and
familiarize yourself with the location of the components.
Tasks
Refer to the README file(s) for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ List the four key features of the Jini programming model and give
an overview of each feature
❑ Start the services that are supplied with the Jini technology
distribution, the JavaSpaces service, and run the demonstration
browser provided with the Jini technology distribution
In the context of the operating systems you use most, think about how you
would deploy a production system built on Jini technology.
● What services need to start when the system boots?
● Are there any web servers already in place that could be used to
provide the classes?
Objectives
Upon completion of this module, you should be able to:
● Describe typical lease scenarios, and the flow of control and data
that occurs in them
4-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Relevance
You must appreciate that when a lease is sent over the network it is
serialized, and this has consequences in terms of timing. If a lease
describes its own expiry time in terms of a clock time, but the clock on
the receiving end is out of synchronization with the sender, the lease
expiry will be uncertain. Similarly, if expiry is in terms of duration, but
the network transit is slow, uncertainties will arise.
Leases 4-3
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
What Is a Lease?
The semantics of the lease can vary between different lease granters. In
some cases, granting a lease offers exclusive use of the related resource
and guarantees a best effort to maintain that resource’s availability. In
other cases, no such exclusivity exists.
Why Leasing?
Leases 4-5
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
In addition to providing for distributed garbage collection, the
appropriate use of leases supports resource management. For example,
a server that offers short leases for its resources can reclaim those
resources more quickly than one that offers long leases. By doing this,
you can reclaim the resource and offer it to other clients on a more
timely basis.
Leases 4-7
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
In general, you should seek the lease only long enough to complete the
operations for which you require the resource. Requesting
unnecessarily long leases makes the whole system less responsive.
From the server’s point of view, it is tempting to try to restrict lease
duration; however, this can be counterproductive. If a server
habitually issues too short a lease, there will be an unnecessary
amount of renewal traffic. Furthermore, if a server allocates short
leases and then denies renewals, clients will be continuously making
abortive attempts to complete work, but never succeeding. For these
reasons, be careful before creating a lease granter that habitually
shortens leases or denies renewals.
Lease Flow – 1
The server keeps track of leases that it has issued and the times at
which they expire. If nothing else happens in the meantime, the server
will time-out the lease and reclaim the associated resource when the
lease expires.
Leases 4-9
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Lease Flow – 2
Leases 4-11
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Basic Lease Flow
Figure 4-1 illustrates the client making a request of the server for a
resource. The server responds by providing that resource with an
associated lease. The client then uses the resource for all or part of the
lease duration, and keeps track of that duration with a timer.
Simultaneously, the server keeps track of the lease using a timer. If the
client timer indicates that the lease duration is nearly expired, the
client can try to renew the lease. If the client completes its work and no
longer requires the resource, the client should cancel the lease. If the
server timer notices that the lease has expired, the server reclaims the
resource.
Leases 4-13
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
The cancel method advises the server that the client is no longer
interested in the resource or its associated lease. You should call the
cancel method as soon as you know you no longer need the resource
to which it relates.
When you issue a request that results in a lease being issued, you
generally provide an indication of the number of milliseconds for
which you want the lease to be granted. Similarly, when requesting
renewal, you send the number of milliseconds that you want to extend
the lease. These time values are represented using a long value. The
lease interface also defines a pair of constant values that are expected
to be used when you request a resource or lease from a server. The
value ANY indicates that the server should grant a lease that is
convenient to it. You have the opportunity to request renewal of the
lease should you later decide you need the resource longer. The value
FOREVER requests the longest lease that the server can grant. Be aware
that FOREVER is not an infinite lease, it is the maximum amount of time
that can be represented by a long value. In the JavaSpaces technology
service, for example, a FOREVER request generally results in a lease of
one hour.
You can serialize the lease, for example, prior to transmission over the
network using either an absolute time format or a delta-time format. If
you use the absolute time format, difficulties might arise if the clocks
of the two systems are not reasonably synchronized, or if the time in
transit is great. If you use a delta-time format, the expiration time of
the lease will be later when it is deserialized. You use the constant
values Lease.ABSOLUTE or Lease.DURATION to choose which form to use
for serialization. The lease grantor is responsible for making this decision.
Leases 4-15
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
The LeaseRenewalManager
Leases 4-17
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Lease Exceptions
Leases can give rise to a variety of exceptions. The base class for all
lease-specific exceptions is net.jini.core.lease.LeaseException,
but in most cases, a more specific exception is thrown.
Implementing Leases
When you use a lease, it is passed from the system that allocates and
holds a resource to another system that is using the resource. The
client system then uses the lease to notify the provider that it still
requires, or has finished with, the resource. This implies that there is
network communication between the lease object on the client and the
lease granter. One possible way to implement this communication
would be to have each lease as an RMI remote object. In such a
scheme, the lease object that is sent to the client would actually be the
remote stub of a lease implementation remote object that remains on
the client.
Leases 4-19
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
In the Landlord leasing scheme, a single remote object (the landlord) is
created on the lease granter system. Individual leases are composed of
a copy of the stub for this object, along with a "cookie". The cookie
serves to identify the leased resource to which this particular lease
object refers.
The Landlord lease classes do not handle lease expiry. Their focus is
solely on the efficient handling of network connections.
Figure 4-3 shows the key relationships between the classes that make
up the Landlord lease mechanism. The Landlord object is an RMI
remote object, and a single instance of it sits on the server system. This
object receives requests from LandlordLease objects that are located
on client systems. Each LandlordLease object carries with it a copy
of the stub that connects to the landlord. When either renew or cancel
is called on the client, this is translated into a call to the Landlord
object, and the "cookie" is sent as the argument of that call. The cookie
is used by the landlord to decide the resource to which this request is
related.
Leases 4-21
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Exercise: Investigating Leasing
Preparation
Review the course notes regarding the APIs of the various lease
classes, and the landlord classes. Run the sample solution, and
examine the code.
Tasks
Refer to the README file(s) in the directory for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Leases 4-23
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Check Your Progress
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ Describe typical lease scenarios, and the flow of control and data
that occurs in them
How would you use this leasing scheme to implement leasing of event
registrations?
Leases 4-25
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Distributed Events 5
Objectives
Upon completion of this module, you should be able to:
5-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Relevance
For a program that runs in a single virtual machine, JDK 1.1, the event
mechanism is extremely robust. Event delivery is performed by direct
method calls, delivery of events is virtually guaranteed, and the order
in which events arrive at their destinations is the same as the order in
which they were dispatched. Provided the event handling methods
that receive these events behave properly (that is, do not take too long
to complete), event delivery is almost instantaneous.
Distributed events and their handlers use the RMI system to dispatch
an event. Because of this, listeners that expect to receive distributed
events publish themselves as remote objects, and declare their
listener methods as possibly throwing remote exceptions.
The third argument is called the handback object. This is a copy of any
serializable object and is in the form of a MarshalledObject. When
the event is dispatched, this object is passed to the listener as one of
the fields of the event. This object can be useful during event
processing. The significance of this object is discussed later in the
module.
Dispatching Events
You can use the marshalled object field, sometimes called the
handback object, for a variety of purposes. It is a copy of the
marshalled object that was passed into the event registration. This
might seem odd, because you would assume that the listener could
obtain this same object locally. Sometimes, it is easier if the event
source handles the association for you. In embedded systems this can
be particularly important, because it can substantially reduce the
storage requirements on the client by placing the memory load on a
server.
Figure 5-1 illustrates the simple case where a client registers for events
to be sent back to itself. There are two remote objects. The event source
is, or has, a remote object that handles the event registration and the
client is, or has, a remote object that implements the
RemoteEventListener interface. The client remote object receives
the dispatched events from the server.
You could use a third party to handle the event for several reasons.
The third party might be better equipped to respond to it, the rate at
which it issues events is high, or a more powerful system is needed to
handle the event.
Figure 5-2 illustrates how you can register an event using one client to
send it to another listener. The same listener can filter events on behalf
of multiple clients, which can either receive the events forwarded
directly or by reference to the handback object.
Event Package
Unlike most of the other aspects of Jini technology, all of the event
features are part of the core APIs. This means that they must be fully
implemented in any Jini technology distribution.
Preparation
Review the course notes regarding the APIs of the various event
classes. Run the sample solution, and examine the code.
Tasks
Refer to the README file(s) in the directory for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
● Write code using the Jini technology distribution classes to use the
Discovery and Announcement protocols.
6-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Relevance
Discussion – Services are the most central part of Jini technology, and
the Lookup service is the means by which services are generally
distributed.
Various classes that support the Discovery protocols are located in the
packages net.jini.discovery. One class, LookupLocator, is in the
package net.jini.core.discovery. You can find additional support
classes in the package com.sun.jini.discovery.
In fact, the Unicast Discovery Protocols form the final stage of the
Multicast Discovery Protocols. That is, even when Multicast Discovery
Protocols are used to locate the registrar, the Unicast Discovery
Protocol messages are used to communicate with the registrar.
Multicast Protocols
Looking Up a Service
To look up a service, you must first locate the Lookup service. You can
do this statically, using the LookupLocator class. The LookupLocator
gives you an object that implements the ServiceRegistrar interface,
this object is your connection to the Lookup service itself, and
provides the lookup method that locates a service.
Once you have located a registrar, you have an object that implements
the interface net.jini.core.lookup.ServiceRegistrar. It is the
methods of this interface that you use to perform operations on the
registrar.
When you are looking for a service, you use the ServiceTemplate
class, which is used for describing the features you require in a service.
You use the ServiceTemplate for both a specific search, using the
lookup methods, and to make requests for notification using the
notify method.
Any or all of the fields in the service template can be null. Each null
field is considered a wild card; that is, it is ignored when attempting to
find a match for the requested service.
The ServiceID field enables you to request a specific service using its
ServiceID value, which is a unique identifying number for a service.
You would typically use this to re-locate a particular service after your
process had crashed and restarted, or after some transient failure had
disconnected you from your chosen service.
You can use the attribute template specified in the array of entry
objects to further qualify successful matches.
Once the LookupLocator object has been created, you call the
getRegistrar method to obtain the ServiceRegistrar object that
provides a connection with the Lookup service.
When you call the lookup method as shown in the example, you are
given at most a single service object. An alternative form of the lookup
method takes an additional int argument and allows you to obtain
multiple services that match your template. The int argument
indicates the maximum number of services about which you want to
be told. The return of this method is a ServiceMatches object.
You can use either or both of the following two classes to dynamically
locate Lookup services. This idea contrasts with the static approach
that was just described.
● LookupLocatorDiscovery
● LookupDiscovery
Both of these classes report the Lookup services that they locate using
local events. The events are delivered to listeners that must implement
the DiscoveryListener interface.
This example adds some dynamic behavior that was not present when
using the LookupLocator alone, and also looks for multiple registrars.
The constructor takes the array of strings it receives and constructs an
array of LookupLocator objects. This array is then used to construct
the instance of the LookupLocatorDiscovery class. The example then
adds itself as a listener to that LookupLocatorDiscovery object, so
that the discovered method is called when any of the listed Lookup
services comes up.
This example monitors the state of the listed Lookup services, but it
takes no notice of other Lookup services that were not listed on the
command line at startup. In this sense, the example still does not
demonstrate fully spontaneous networking.
● ServiceTemplate tmpl
● int transitions
● RemoteEventListener listener
● java.rmi.MarshalledObject handback
● long leaseDuration
The last three of these arguments are the standard arguments for an
event registration and should be familiar. The first, the
ServiceTemplate object, describes the types of service about which
you want to be notified. The second, called transitions, describes
the type of change you in which you are interested.
You can also get transitions based on attributes. For example, a printer
with a status of offline might be in a nomatch state compared to your
template, but when its attribute is changed to online, this might
constitute a TRANSITION_MATCH_NOMATCH. Changing attributes can
also give rise to the TRANSITION_MATCH_MATCH. This transition implies
that some attribute changed, but that attribute was not part of your
template.
Registering Services
When you write a service, you need to register it with one or more
Lookup services. Typically you register a service using the register
method of the ServiceRegistrar class.
You use the ServiceItem class when registering a new service. This
class supports the specification of three elements: the ServiceID,
Object, and Entry [] fields.
The first field can carry a unique identifying number. This number, the
ServiceID, can be returned by the registrar the first time the service is
registered. For subsequent registrations of the same service, explicitly
state the ServiceID. If the same service is registered with multiple
registrars or is re-registered with the same registrar later (perhaps after
the registrar has been restarted after a period), the new service
registration is recognized by clients as the same service.
The service itself is carried in the Object field. The only requirement
for this element is that you must be able to serialize this object.
Therefore, this field should not be null when registering a service.
Registration also returns a lease. For as long as you want your service
to remain registered, you must periodically renew this lease. If the
lease expires, your service is removed from the registrar automatically.
This behavior ensures that registrars do not become cluttered with
entries describing services that are no longer available. You can use the
support class, com.sun.jini.lease.LeaseRenewalManager, to help
renew the lease.
If this is the first time this service is being registered, you do not
provide a ServiceID. Instead, use one of the constructors of the
JoinManager that does not require this, but instead takes a
ServiceIDListener. The ServiceIDListener gets callbacks when
the service is allocated an ID. Preserve this ID so that you can reuse it
later if you need to re-register the same service. When you re-register a
service, perhaps after a period of downtime, be sure to register it
under the previously supplied ServiceID so that it is clear to
interested parties that this is the same service as before.
When designing a new service, you should first identify the interface,
or interfaces that will characterize it. These interfaces are used by
interested clients to perform the lookup that allows them to locate
your service. In this case, there are two methods in the interface. Of
these, one is intended for use by a generalized service registration
application, not by the clients. The method that is intended for use by
clients is getUI. This method allows a client to obtain a
java.awt.Component instance from the service proxy. When
displayed, that user interface should provide the user with a means of
interacting with the service.
1 import java.awt.*;
2 import net.jini.lookup.entry.ServiceType;
3
4 public class MyServiceType extends ServiceType {
5 public String type = “An Applet”;
6
7 public Image getIcon() {
8 return null;
9 }
10
11 public String getDisplayName() {
12 return “Counting Applet”;
13 }
14
15 public String getShortDescription() {
16 return “This is an applet that counts”;
17 }
18 }
Code 6-8 MyServiceType.java
Non-Core Classes
Preparation
Run the sample solutions provided for module 7. Examine the
behavior.
Tasks
Refer to the file README files in the directory for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ Write code using the Jini technology distribution classes to use the
Discovery and Announcement protocols.
Objectives
Upon completion of this module, you should be able to:
7-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Relevance
The MapAll class also registers with each Lookup service that is
located, asking for notification about any services that are added,
removed, or modified.
As part of its basic construction, the MapAll class can issue events
(local, not distributed) to any registered listener when changes of the
type just outlined occur. This allows you to use it as the basis of a
general service browsing facility.
The HashMap called servMap (line 44) contains the service proxies for
the registrar, indexed by serviceID.
The next step is to collect the current list of all the registered services
in this Lookup service. This is achieved in the populateRegistrarMap
method call (line 191). After the map has been populated, the method
notifyServicesChanged is called (line 198) to populate the main list
of services maintained in the HashMap services (line 26) and send
events to registered ServiceListener objects.
The final sample is the code that generates the browser used to display
a dynamically updated list of services. The Browse class is a
ServiceListener (line 14) that uses MapAll to tell it when services
are either arriving or leaving.
The Browse constructor (lines 67-106) builds the user interface. The
notifyServices method (lines 108-143) is a listener method that
gets called by MapAll when a service becomes available or is removed.
The list of available services is updated and rendered in the display,
using the entries that comprise the currently available services.
To start the main services, you can use the generalized script. You start
the service provider using a commands similar to the following:
1 #!/usr/bin/ksh
2
3 HOST=$(hostname)
4
5 export JINI_HOME=${HOME}/jini1_0
6 export CLASSPATH=.:${JINI_HOME}/lib/jini-
core.jar:${JINI_HOME}/lib/jini-ext.jar:${JINI_HOME}/lib/sun-util.jar
7
8 java \
9 -Djava.security.manager \
10 -Djava.security.policy=./policy.all \
11 -Djava.rmi.server.codebase=http://${HOST}:8081/ \
12 Joiner http://${HOST}:8081/ Service1 $*
13
Code 7-3 runservice
You start the client (browser) with commands similar to the following:
1 #!/usr/bin/ksh
2
3 HOST=$(hostname)
4
5 export JINI_HOME=${HOME}/jini1_0
6 export CLASSPATH=.:${JINI_HOME}/lib/jini-
core.jar:${JINI_HOME}/lib/jini-ext.jar:${JINI_HOME}/lib/sun-util.jar
7
8 java \
9 -Djava.compiler=NONE \
10 -Djava.security.manager \
11 -Djava.security.policy=./policy.all \
12 -Djava.rmi.server.codebase=http://${HOST}:8082/ \
13 Browse $*
Code 7-4 runbrowser
Like the service installer, the client also requires that you specify the
security options on the command line. In addition, you specify the
rmi codebase there. The arguments to the program are explicit lookup
locators that you can use to direct the browser to use Lookup services
that are not found using the Multicast protocols.
Preparation
Decide on a simple type of service you could usefully communicate
with its original host. An editor, using the original host as a storage
medium is a good example.
Tasks
Refer to the README file(s) for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
● Outline the states that a Jini transaction can be in, and state the
significance of each state
8-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Relevance
Transaction States
Starting a Transaction
Once the transaction has been created, interested parties can join it. To
join a transaction, you need the remote reference to the
TransactionManager and the ID of the created transaction. This ID
is contained in the TransactionManager.Created object. Because
other participants might need to renew the lease on the transaction,
the entire TransactionManager.Created object is often passed to
all transaction participants.
Failure of a Transaction
Rejoining a Transaction
In the go method, the Trans1 object first asks the transaction manager
to create a new transaction. The response to this request is returned in
the TransactionManager.Created object. Next, a second Trans1
object is created, so that there are two participants in the transaction.
Next, the first Trans1 object attempts to join the transaction that it
created, and then calls the connectWith method to join the second
participant to the transaction. After both participants have been joined,
the first participant makes a random decision about how to complete
the transaction, either committing or aborting it.
Preparation
Run the sample solution, and examine its behavior. Look at the code to
get an idea of how it is structured.
Tasks
Refer to the README file(s) for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
❑ Outline the states that a Jini transaction can be in, and state the
significance of each state.
Objectives
Upon completion of this module, you should be able to:
9-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Relevance
Discussion – In a distributed system, what tools can you use that will
store data, or provide for communication? What facilities do these
tools offer for zero administration, and storage of arbitrary objects
(state and behavior)?
While most modern databases are aware of a network, they use the
network in a comparatively limited way. Generally, they are simple
client server configurations involving only two systems at one time.
With JavaSpaces technology, you can involve many systems
simultaneously. One machine can be running the JavaSpaces
technology service, another system performing a write to that space,
while two other systems are being notified that the write has occurred.
Before you can use a database, you must first define the schema for
that database. Once defined, this schema is rigidly applied to every
record that is stored in the database. On the other hand, every object in
a space is written to the space independently and requires only
adherence to some simple structuring rules. These rules state little
more than that the entry must be serializable.
Although you can use features like triggers, a database does not
usually inform other parts of a distributed system when a record is
written into it. By contrast, such notification is fundamental to the
nature of the JavaSpaces technology. You can ask for such notification
when a particular type of object, perhaps one with particular values in
certain fields, is written into it.
Most databases are configured and installed to run on one host system.
Migrating the database to a different system can be time consuming,
and if the new system is a different type, even impossible. JavaSpaces
technology software is written in the Java programming language and
as such is platform independent. Furthermore, moving a JavaSpaces
technology service from one system to another, or perhaps even
replicating it, can be a simple matter.
Storing an Entry
● Implement net.jini.core.entry.Entry
● Extend Serializable
● Use net.jini.entry.AbstractEntry
● public
● Serializable
● Not transient
● Not final
● References
A side effect of this storage format is that if two fields in an Entry are
references to the same object, by the time the Entry is retrieved from
the JavaSpaces software, the two fields are references to two distinct,
but identically composed, objects. This occurs only with fields at the
top level of the Entry.
If more than one entry in the space matches the request, it is arbitrary
which is returned. You must consider this when you design a system
using JavaSpaces technology. It is difficult to be sure that you have
read all matching entries; in fact, unless you remove the entries (using
the take operation that will be introduced shortly) and then put them
all back afterwards, you cannot be sure you have read all matching
All four operations take a long argument as their third parameter. This
is a time-out period. In the case of the xxxxIfExists methods, this
time-out determines how long the method waits for a matching entry
that is currently locked by a transaction. These methods return only
entries that are present at the time the call is issued.
The simple forms of these methods, read and take, have a slightly
different interpretation of the time-out. If a matching entry is locked
by a transaction, these methods wait for it to be released as is the case
with the xxxIfExists methods. However, if no matching entries
exist when the method call is issued, these methods wait to see if a
matching entry is written to the space during the time-out period.
You use the write method of the JavaSpace interface to place new
objects into the storage. The first argument is the object to be stored,
the second (if non-null) is the transaction that applies to this write. If
the transaction subsequently fails, it will be as if the write never
occurred. The third argument is the requested lease time. If the write
succeeds, it returns a lease. This lease relates to the use of the storage
space in the space. If you allow this lease to expire, the entry is
removed from the space.
It is significant that in this example, neither the client nor the server
need to be configured in any way to know about each other. There can
be multiple servers, allowing additional reliability and a form of load
balancing to occur automatically.
This class acts as a container for the work that is to be done. It forms a
recognizable wrapper, allowing servers to spot a job when it is written
into the space. To support this, the class must have three features; it
must be a valid entry in a space, it must have a field that distinguishes
new from completed jobs, and it must have a field that allows the
submitter of the job to uniquely identify the job in such a way that it
can retrieve its own jobs on completion, and ignore those of other
submitters. To add to the utility of the class, a third field is provided
that can be used to store the results of the job. This could be achieved
by providing fields in the specific subclass that carries the job.
However, only public fields are stored in a space, so this approach
allows you to create a special "capsule" class that stores the results in
this field, while perhaps keeping the data values themselves private.
The client code starts by locating an available spaces service, and then
treats each command-line argument as a job. These job classes are
loaded, instantiated, and submitted for execution by the submit
method.
The server code is even simpler than the client code. In this case, all
that has to be done is to locate the spaces service, and attempt to read
a job from it. The job must be in the AWAITING_EXECUTION state,
and this is arranged by using a raw RunnableEntry as a template for
the read operation. After the run method completes, the job is written
back into the space. The state of the job must be changed to
EXECUTION_COMPLETE but this is handled by the job itself.
Preparation
Study the source for the example in the notes. You will use this as the
starting point for your transaction protected variation.
Tasks
Refer to the README file(s) for this module.
● Experiences
● Interpretations
● Conclusions
● Applications
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Objectives
Upon completion of this module, you should be able to:
A-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A
Relevance
Always make sure that any class moved across the network is
serializable. Often you implement the Serializable interface
indirectly by specifying that a class implements some other interface in
a Jini technology package; for example, Entry. This makes it easy to
forget that in some cases you must implement the Serializable
interface directly.
You must ensure that the clients know how and where to download
classes. You can do this in one of two ways. Conventionally, you can
set the property java.rmi.server.codebase. This tells clients where
to load classes that were loaded locally by their original servers.
Alternatively, any class that is loaded by an instance of the
URLClassLoader is correctly annotated for loading by clients.
Although these two mechanisms enable you to specify where classes
should be loaded from, it important to remember that the URLs you
use when specifying a code base must be absolute, not relative. That is:
these URLs must have fully qualified domain names and full paths;
Again, obscure exceptions can result in classes not being available for
download.
Service Requirements
Multicast Issues
Before continuing on to the next module, check that you are able to
accomplish or answer the following:
Please
Recycle