You are on page 1of 308

Programming Distributed Services

With Jini Technology

SL-370

Student Guide

Sun Microsystems, Inc.


MS BRM01-209
500 Eldorado Boulevard
Broomfield, Colorado 80021
U.S.A.

Revision A, October 1999


Copyright 1999 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompi-
lation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and
its licensors, if any.

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.

Postscript is a trademark of Adobe Systems Incorporated.


U.S. Government approval required when exporting the product.

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

ii Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Preparation...............................................................................3-34
Tasks .........................................................................................3-34
Exercise Summary...................................................................3-35
Check Your Progress ...................................................................... 3-36
Think Beyond .................................................................................. 3-37
Leases............................................................................................................4-1
Objectives ............................................................................................4-1
Relevance............................................................................................ 4-2
Jini Distributed Leasing Terminology ........................................... 4-3
What Is a Lease? ................................................................................ 4-4
Why Leasing? .................................................................................... 4-5
Characteristics of the Lease ............................................................. 4-7
Lease Flow – 1.................................................................................... 4-9
Lease Flow – 2.................................................................................. 4-10
Basic Lease Flow.............................................................................. 4-12
Lease Flow With LeaseRenewalManager................................... 4-13
The Lease Interface ........................................................................ 4-14
The LeaseRenewalManager.......................................................... 4-16
Lease Exceptions ............................................................................. 4-18
Implementing Leases...................................................................... 4-19
Landlord Lease Classes .................................................................. 4-21
Exercise: Investigating Leasing ..................................................... 4-22
Preparation...............................................................................4-22
Tasks .........................................................................................4-22
Exercise Summary...................................................................4-23
Check Your Progress ...................................................................... 4-24
Think Beyond .................................................................................. 4-25
Distributed Events .....................................................................................5-1
Objectives ............................................................................................5-1
Relevance............................................................................................ 5-2
Comparing Local and Distributed Events..................................... 5-3
What Are Distributed Events? ........................................................ 5-4
Event Registration (Typical)............................................................ 5-6
Dispatching Events ........................................................................... 5-8
Simple Distributed Event Flow..................................................... 5-10
Third-Party Event Handling ......................................................... 5-11
Event Package.................................................................................. 5-14
Exercise: Remote Event Listener................................................... 5-15
Preparation...............................................................................5-15
Tasks .........................................................................................5-15
Exercise Summary...................................................................5-16
Check Your Progress ...................................................................... 5-17
Think Beyond .................................................................................. 5-18

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

iv Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Exercise Summary...................................................................7-19
Check Your Progress ...................................................................... 7-20
Think Beyond .................................................................................. 7-21
Jini Transactions.........................................................................................8-1
Objectives ............................................................................................8-1
Relevance............................................................................................ 8-2
What Are Jini Transactions? ............................................................ 8-3
Transaction States ............................................................................. 8-5
Starting a Transaction....................................................................... 8-7
Successfully Completing a Transaction ......................................... 8-9
Failure of a Transaction.................................................................. 8-10
Rejoining a Transaction.................................................................. 8-12
Transactions and Concurrent Access ........................................... 8-13
Transactions Example .................................................................... 8-15
Additional Transaction Classes .................................................... 8-19
Exercise: Investigating Transaction Sequencing ........................ 8-22
Preparation...............................................................................8-22
Tasks .........................................................................................8-22
Exercise Summary...................................................................8-23
Check Your Progress ...................................................................... 8-24
Think Beyond .................................................................................. 8-25
JavaSpaces Technology.............................................................................9-1
Objectives ............................................................................................9-1
Relevance............................................................................................ 9-2
Overview of JavaSpaces Technology ............................................. 9-3
Using JavaSpaces Technology Services ......................................... 9-5
Comparing JavaSpaces Technology Services and Databases..... 9-7
Storing an Entry ............................................................................. 9-12
JavaSpace Interface Methods....................................................... 9-14
JavaSpace Interface Methods....................................................... 9-16
Example Using JavaSpaces Technology Services....................... 9-18
The RunnableEntry Class............................................................. 9-20
The MPCClient Class...................................................................... 9-21
The MPC Class................................................................................... 9-24
The Jobs ............................................................................................ 9-26
Exercise: Transactions and Spaces................................................ 9-28
Preparation...............................................................................9-28
Tasks .........................................................................................9-28
Exercise Summary...................................................................9-29
Check Your Progress ...................................................................... 9-30
Think Beyond .................................................................................. 9-31
Common Pitfalls........................................................................................A-1
Objectives ...........................................................................................A-1
Relevance........................................................................................... A-2

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

vi Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
About This Course

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

This course contains nine modules. These modules describe Jini


technology; that is, "the vision behind Jini technology" and how to
design and implement distributed systems using the APIs.

viii Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Course Map

The following course map enables you to see what you have
accomplished and where you are going in reference to the course goal:

Introduction to Essentials of Investigating


Jini the RMI Jini
Technology System Technology

Leases Distributed
Events

Lookup and Putting it Together


Discovery

Jini Transactions

JavaSpaces
Technology

About This Course ix


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Module-by-Module Overview

This course contains the following 9 modules:

Module 1 - "Introduction to Jini Technology," contains a qualitative


discussion covering what you can expect to achieve when
programming with Jini software.

Module 2 - "Essentials of the RMI System," examines RMI, and looks at


the technicalities of using RMI to write programs.

Module 3 - "Jini Technology Overview," briefly covers the five main


parts of Jini technology. This discussion is intended to give you a
relatively technical overview of Jini technology and the way it
interacts. Code is not examined in this module.

The next four modules, Module 4, "Jini Distributed Leasing,"


Module 5, "Jini Distributed Events," and Module 6, "Jini Lookup and
Discovery" describe individual aspects of Jini technology. Sample code
is provided in these sections, although not every section has a full
example of its own.

x Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Module 7 - "Putting It Together," looks at a substantial example of
using the Jini Lookup service. The example has been used in module 6
as support for some of the lab exercises.

Module 8 - "Jini Transactions," describes the distributed transaction


framework provided by Jini technology.

Module 9 - "JavaSpaces Technology" introduces JavaSpaces™


technology which, while not part of the Jini technology distribution,
often finds application in the same type of distributed applications.

Appendix A, "Common Pitfalls," describes a number of common


mistakes, and how to avoid them. The information in this section will
help you when you are writing real code with the Jini technology. This
appendix is provided for your reference, but if time permits, it can be
discussed in class.

About This Course xi


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Course Objectives

Upon completion of this course, you should be able to:

● Describe the Jini technology vision

● Use the Jini Lookup and Discovery facilities to create "spontaneous


networking"

● Use leases to create distributed applications that are robust in the


face of network or system failures

● Use distributed events to create highly dynamic and responsive


distributed systems

● Use transactions to create complex distributed systems that are


robust in the face of network or system failures

● Use JavaSpaces technology to provide distributed communication

xii Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Skills Gained by Module

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

Describe the Jini technology vision


Use the Jini Lookup and Discovery facilities to
create "spontaneous networking"
Use leases to create distributed applications that
are robust in the face of network or system
failures
Use distributed events to create highly dynamic
and responsive distributed systems
Use transactions to create complex distributed
systems that are robust in the face of network or
system failures
Use JavaSpaces technology to provide distributed
communication

About This Course xiii


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Guidelines for Module Pacing

The following table provides a rough estimate of pacing for this


course:

Module Day 1 Day 2 Day 3 Day 4 Day 5

About This Course A.M.


Introduction to Jini technology A.M.
Essential RMI P.M.
Investigating Jini technology A.M.
Leases P.M.
Distributed events A.M.
Lookup and discovery P.M. A.M.
Putting it together P.M.
Jini transactions A.M.
JavaSpaces technology P.M.

xiv Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Topics Not Covered

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:

● Programming in the Java™ programming language – Covered in


SL-275 Java Programming.

● Using the RMI activation facilities – Covered in SL-301 Distributed


Programming with Java

Refer to the Sun Educational Services catalog for specific information


and registration.

About This Course xv


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
How Prepared Are You?

This course is intended for programmers who are experienced with


the Java programming language, but is also suitable for high-level
system architects who, while perhaps not practicing programmers, are
familiar with the nature of the Java programming language, and are
comfortable discussing the Java application programming interfaces
(APIs). You are not expected to be familiar with Java RMI, as this
course introduces the essential aspects of that technology. However, if
you have used RMI, you will find that experience is beneficial to your
overall understanding of this course.

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.

At the present time, Jini technology is built on the security


mechanisms that are built into the Java 2 technology platform. In the
future, a security scheme will be introduced for Jini technology.
However, because this is not currently available, this course does not
discuss these matters.

xvi Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Between each module, time is allocated for a short break. These breaks
provide an opportunity for refreshment, relief of aching muscles, and
general discussion. However, do not feel that you must necessarily
limit your questions to the breaks. If you want to ask a question that
extends any particular discussion, ask it at the end of the module as it
might be covered in the next module. However, if you do not
understand a particular subject, ask for clarification immediately. You
might not be the only person with a problem, and there is little point
in proceeding with the remainder of a discussion if you have questions
about the first part of the discussion.

About This Course xvii


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Introductions

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.

xviii Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
How to Use Course Materials

To enable you to succeed in this course, these course materials employ


a learning model that is composed of the following components:

● Objectives – What you should be able to accomplish after


completing this module is listed here.

● Relevance – This section, which appears in every module,


provides scenarios or questions that introduce you to the
information contained in the module and provoke you to think
about how the module content relates to.

● Overhead image – Reduced overhead images for the course are


included in the course materials to help you easily follow where
the instructor is at any point in time. Overheads do not appear on
every page.

About This Course xix


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
How to Use Course Materials

● Lecture – The instructor will present information specific to the


topic of the module. This information will help you learn the
knowledge and skills necessary to succeed with the exercises.

● Exercise – Lab exercises will give you the opportunity to practice


your skills and apply the concepts presented in the lecture.

● Check your progress – Module objectives are restated, sometimes


in question format, so that before moving on to the next module
you are sure that you can accomplish the objectives of the current
module.

● Think beyond – Thought-provoking questions are posed to help


you apply the content of the module or predict the content in the
next module.

xx Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Course Icons and Typographical Conventions

The following icons and typographical conventions are used in this


course to represent various training elements and alternative learning
resources.

Icons
Additional resources – Indicates additional reference materials are
available.

Demonstration – Indicates a demonstration of the current topic is


recommended at this time.

Discussion – Indicates a small-group or class discussion on the current


topic is recommended at this time.

Exercise objective – Indicates the objective for the lab exercises that
follow. The exercises are appropriate for the material being discussed.

Note – Additional important, reinforcing, interesting, or special


information.

About This Course xxi


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Typographical Conventions
Courier is used for the names of commands, files, and directories, as
well as on-screen computer output. For example:

Use ls -al to list all files.


system% You have mail.

It is also used to represent parts of the Java™ programming language


such as class names, methods, and keywords. For example:

The getServletInfo method is used to...


The java.awt.Dialog class contains Dialog (Frame parent)

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.*;

Courier italic is used for variables and command-line


placeholders that are replaced with a real name or value. For example:

To delete a file, type rm filename.

Palatino italics is used for book titles, new words or terms, or words
that are emphasized. For example:

Read Chapter 6 in User’s Guide.


These are called class options.
You must be root to do this.

xxii Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
The Java programming language examples use the following
additional conventions:

● Method names are not followed with parentheses unless a formal


or actual parameter list is shown. For example:

"The doIT method..." refers to any method called doIt.

"The doIt() method..." refers to a method called doIt which takes


no arguments.

● Line breaks occur only where there are separations (commas),


conjunctions (operators), or white space in the code. Broken code
is indented four spaces under the starting code.

● If a command is different on the Solaris™ and Microsoft Windows


platforms, both commands are shown. For example:

On Solaris

cd server_root/bin

On Microsoft Windows

cd server_root\bin

About This Course xxiii


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Acronyms

A significant number of acronyms are used in this course guide. These


are expanded here, so that you have a conveniently located reference
for any terms that are unfamiliar to you.

API Application Programming Interface

CPU Central Processing Unit

DHCP Dynamic Host Configuration Protocol

HTTP HyperText Transport Protocol

JDC Java Developers Connection

JDK Java Development Kit

JRMP Java Remote Method Protocol

JVM Java Virtual Machine

RMI Remote Method Invocation

TCP/IP Transmission Control Protocol/Internet Protocol

UDP User Datagram Protocol

URL Uniform Resource Locator

xxiv Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Introduction to Jini Technology 1

Objectives
Upon completion of this module, you should be able to:

● Recognize the elements of the Jini technology distribution

● State the meaning of the terms “spontaneous networking” and


“plug and work”

● Describe the key difference between RMI/Jini technology and


traditional distributed computing systems

● Outline the mechanism by which you can move Java technology


classes

1-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
Relevance

Discussion – For what purpose, do you think Jini technology is


designed? What are its strengths and limitations?

1-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

The Vision Behind Jini Technology

Jini technology is about spontaneous networking; that is, networking


that allows systems, devices, and services to be connected to a network
easily. These services are then made available to all other facilities on
the network.

Jini technology blurs the distinction between devices and software; it


is common in Jini systems to refer to services, regardless of whether
they are hardware, software, or some combination of both. This
blurring occurs because when hardware is plugged into the network, it
has its own driver code that is distributed by the Jini technology
infrastructure to wherever it is needed. In the same way, a new
software service is distributed to wherever it is needed.

From a client application’s point of view, both software and hardware


services are handled in exactly the same way. Indeed, some services
that appear to be hardware services are in fact software or services that
appear to be software might be hardware. A printer can be a piece of
software designed to forward the printing job to an email or fax
service. A computation service that appears to be software could
actually be implemented in specially designed hardware.

Introduction to Jini Technology 1-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
The phrase plug-and-work has been coined to describe the way in
which Jini technology removes the need for complex installation and
configuration. Rather than connecting a printer to a network and then
installing drivers for that printer on all systems that might want access
to it, you simply plug in the printer and the Jini technology
infrastructure distributes the handler code, in the form of a service, to
any system that has print jobs.

Another feature of spontaneous networking is that it avoids the need


for administration. In particular, services are located by capability, not
by name. If services have names, this immediately requires
administration at both the service provider (to provide the name) and
the user of the service (to add the name to a list).

1-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

Virtual Demonstration

Although it is easiest to grasp the functionality and behavior of Jini


technology in the context of devices, such as printers, the applicability
of Jini technology is by no means so limited. This discussion talks
about devices first, but then introduces non-device-based Jini systems.

Imagine you are on a plane, writing a document on your laptop


computer. You realize that you have forgotten to bring your portable
inkjet printer, and you must have a hardcopy of this document on
arrival at the client’s site. Fortunately, both you and the plane are Jini-
enabled, and the plane has a printer on board. You simply plug your
laptop into the plane’s network (perhaps this is simply an infrared link
so there are no cables). You bring up your editor’s print menu and one
printer is listed. This is the printer on the plane; you select it and pick
up your printed document in time for a short rest so you can arrive
refreshed at your client’s site.

Introduction to Jini Technology 1-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

What Is Happening on the Plane?

What happened here? First, your computer was recognized by the


plane’s network without the need for configuration. This is not the
domain of Jini but is practical today with network configuration
systems, such as Dynamic Host Configuration Protocol (DHCP). In
situations of this type, radio- or infrared-based networks are
particularly attractive, because network connection is achieved simply
by proximity.

Once connected to the network, your laptop searches for a "Lookup


service." The Lookup service is a core facility in the Jini technology,
and provides much of the spontaneity of the system. The request is in
the form of a multicast User Datagram Protocol (UDP) packet. This
type of packet is not directed at a particular system, but at a family of
systems. Because of this, you do not need to configure your system
with any machine names on the local network.

The Lookup service acts as a repository of services. A service can be


any type of software, but is represented by a service proxy. The service
proxy is a serializable Java technology object that is sent to the client
so that the client can use the service itself. Because the service proxy is

1-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
written by the service provider, the proxy and the service can
communicate in any way that suits the service writer. It might be
useful to think of the service proxy as a self-installing "device driver"
for the service.

An important feature of the Jini Lookup service is the way in which a


request for service is described. In conventional networked systems,
requests are generally made in terms of a name. The problem is that a
name immediately requires some kind of configuration. You must give
the service a name, and that name must be unique in the domain. In
addition, the client needs to be configured with the name of the
services that are appropriate to it, or at the least, the user needs to
know what names relate to what services and functionality to enable
the user to make the proper choice. In contrast, the Jini Lookup service
expects a request to be described in terms of the capabilities of the
requested service. Capabilities are described using interfaces in the
Java programming language. For example, a request for a printer
might be made by asking for a service that implements an interface
called org.jini.BasicPrinter (this is an imaginary interface name).
In this way, no names are used, only descriptions of the required
capabilities.

Introduction to Jini Technology 1-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

More About Services

You have seen that a service is located by specifying its interface,


which allows a service to be any type of software. Although the
example of a printer uses hardware, it is equally possible for a service
to be implemented entirely in software. For example, a spell checking
system can be a service. From the point of view of the client, there is
no difference between a hardware-supported service and a pure
software service. Consider two services that both implement the
BasicPrinter service, one is a physical printer, the other actually
generates a Postscript™ file, or uses email to send the text elsewhere.
To the client, there is no difference.

In addition to the implementation of the service being irrelevant to the


client, so is the location at which the service executes. Two extremes of
location are possible, along with a range of variations in between. On
one hand, a service might execute almost entirely on a single host. In
this case, the service proxy would be an RMI stub that immediately
passes all requests to the main server for execution. On the other hand,
there is no requirement to have any part of a service on a central
system. Instead you can implement a service proxy in such a way that

1-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
the proxy itself performs all the work involved in providing the
service. In practice, a combination of the two is often the most effective
approach, and is equally possible.

In addition to providing one or more interfaces that define the


functionality of that service, the service can also record attributes in
the Lookup service. These attributes serve two purposes. First, they
can assist in deciding which particular service to use if more than one
exists that provides the required functionality. For example, a printer
might carry an attribute that describes its location, and this could
allow you to choose the nearest location. The second purpose of
attributes is to carry status information. For example, in the case of a
printer, you might decide to select a printer that has a "status" attribute
of "online."

Another feature of the service proxy is that it is not restricted to


implementing only a single function. In particular, it is often useful to
have a service implement some kind of control/configuration user
interface. In this way, for example, a printer service might provide a
graphical user interface (GUI) feature that allows you to select the
paper tray, resolution, and so on, for that particular print job.

Introduction to Jini Technology 1-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

Distributed Computing Requirements

For any distributed computing system to work, there must be prior


agreement between the parties involved regarding the
communications protocol, the format of data, and the format of
requests and responses.

Different existing protocols address these issues at various levels.


Transmission Control Protocol/Internet Protocol (TCP/IP), for
example, provides a powerful and flexible communications protocol
that enables processes to send any form of message to one another.
However, it does not address the content or format of those messages.
Furthermore, the semantic meaning of those messages is left up to the
processes themselves. Some higher level protocols address some of
these issues, but usually do so in a way that restricts the use of the
protocol to a specific area.

1-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

Distributed Computing Concepts

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.

Introduction to Jini Technology 1-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

Moving Code

In Java technology, the low-level representation of the program uses a


single language, called the bytecode language, regardless of the
execution platform’s hardware type. Similarly, data formats are
standard regardless of platform. These features ensure that a program
written in the Java programming language executes equally well on
any host platform, regardless of the hardware type.

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.

1-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1

How Code Moves

Moving code in a Java technology system is simple and is performed


by a classloader. The classloader reads the contents of a .class file
into memory. The resulting byte array is subjected to various checks
that are part of the security system, and is then converted into an
internal class definition that is installed in the virtual machine as a
new class.

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.

Introduction to Jini Technology 1-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
Discussion: Applications of Jini Technology

Discussion – Take ten minutes to consider different ways in which


you envision using Jini technology. Try to avoid restricting yourself to
a single category of applications. At the end of this time, be ready to
give brief descriptions to the class of the two uses you consider most
unusual. Keep the descriptions short (no more than two sentences) but
do not restrict yourself to “today’s technology” instead, allow yourself
a little leeway if a technology that is not widely distributed today
would make an interesting application possible.

1-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Recognize the elements of the Jini technology distribution

❑ State the meaning of the terms “spontaneous networking” and


“plug and work”

❑ Describe the key difference between RMI/Jini technology and


traditional distributed computing systems

❑ Outline the mechanism by which you can move Java technology


classes

Introduction to Jini Technology 1-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
1
Think Beyond

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?

1-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Essentials of the RMI System 2

Objectives
Upon completion of this module, you should be able to:

● Describe the essential features of RMI

● State the purpose of the remote interface in an RMI system

● List the steps required to build stubs for an RMI system

● State the purpose of the rmiregistry

● 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

● Install and configure the security manager

● State the problems that arise if a security manager is not installed


in an RMI system that must download classes

2-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Relevance

Discussion – The Remote Method Invocation (RMI) is the foundation


of almost all of Jini technology. A thorough understanding of the
mechanisms by which a fully distributed RMI system is deployed is
essential to the successful implementation of any Jini technology
system.

2-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Introducing RMI

RMI allows you to invoke methods on an object (known as the remote


object) under the control of code running in a different virtual machine.
The virtual machine that invokes the method communicates with the
virtual machine that hosts the remote object using network protocols;
therefore, the two virtual machines can be widely separated.

To invoke a method remotely, three items must be described.

● 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.

● The invoking system must supply an argument list containing


elements of the correct types.

● 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

Essentials of the RMI System 2-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
between machines. The description of the argument and return values
is largely the job of the serialization mechanisms, while the remaining
protocol aspects are described by the Java Remote Method Protocol
(JRMP.) In most situations, you do not need to know the details of
these protocols, just how to use the APIs that invoke them.

An interesting feature of RMI is that it allows the Java Virtual Machine


(JVM) to download a class that was not statically configured into that
JVM. This feature is central to the behavior of Jini technology. Initially,
however, the following discussions will overlook this aspect for the
sake of simplicity.

2-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

How an RMI Call Works

The diagram in Figure 2-1 illustrates how an interface definition is


used to describe the methods that are accessible from a remote object.
The remote object implements this interface, which is used by the
client to declare a variable that refers to an object called the stub. The
stub is generated using the rmic command. The stub accepts method
calls at the client, which is why it implements the interface you
originally declared, and then invokes the implementing method call in
the server across the network on your behalf. The stub then retrieves
the return value from the remote method called and passes it back to
your machine.

To complete this sequence of operations, the stub must prepare the


method arguments for transmission over the network (that is, serialize
them) and the appropriate instructions so that the server will "know"
what method is to be invoked. These instructions and the method
arguments are sent to the remote method. The stub then waits for and
receives the results.

Essentials of the RMI System 2-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Figure 2-1 Operation Flow in a Basic RMI Method Call

2-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

How RMI Works

In most cases, the argument to and return values of remote method


calls are serialized and copied across the network. This is important
because it means that the semantics of remote method calls are pass-
by-object value. This differs from the normal semantics of an ordinary
Java method call, where the method call semantics are pass-by-
reference value.

However, there is an exception to this pass-by-object value behavior. If


an argument in a remote method call is itself a remote object, what is
passed across the network is not a serialized copy of the original
object, but rather a serialized copy of the stub. In this case, the
semantics are pass-by-reference value.

Essentials of the RMI System 2-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Whenever arguments are passed into a remote method call, or a return
value is received from one, the values might be instances of a class that
is not known to the receiving virtual machine. For example, when a
reference to a remote object is first obtained, the object that is passed to
the client from the Lookup service is an instance of the stub for that
remote object. If the stub has not been installed on the client, the stub’s
defining class must be loaded before the stub can be deserialized for
use. This class loading can happen automatically in both the client and
the server provided the appropriate configuration has been performed.

2-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Another Perspective

You can look at the preceding discussions from another perspective.


The serialized form of an object defines the state of that object, while
the class file associated with the object defines the behavior as well as
the template for constructing new instances of that class. Because both
of these are a sequence of bytes, they can be moved between systems
over a network. The RMI system uses these concepts to pass
arguments and return values over the network. The ability to move
class files means that if arguments are subclasses of the formal
parameter types declared in the interfaces, and the class of the object
being transmitted is unknown to the receiver’s virtual machine, you
can load the defining class for the value.

Essentials of the RMI System 2-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Two RMI Programming Models

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.

A variation of this model allows the stub to be unknown to the client


prior to the time that the client looks up the service. In this variation
(which is probably the most common way to use RMI), the class file
that defines the stub is downloaded to the client during execution.

2-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Two RMI Programming Models

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.

Essentials of the RMI System 2-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

A Minimal RMI Example

This example demonstrates the fundamental features of an RMI


system. The work that is done by the example is trivial, but serves to
demonstrate the important aspects without confusing the issue with a
complex algorithm.

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.

2-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
A Minimal RMI Example – The Interface

Code 2-1 import java.rmi.*;

1
2 public interface TellMeServer extends Remote {
3 public String tellMe(String question) throws RemoteException;
4 }
Code 2-2 TellMeServer.java

The interface defined in this example declares a method tellMe with


its argument and return types. The intention is that the RMI server
object implements this interface, and the RMI system, by means of the
automatically generated stub class, exports this particular method so
that it is available for invocation over the network.

The interface extends the interface java.rmi.Remote, which marks


this as the remote interface of an RMI server object.

The arguments and return value must be serializable objects, although


it is permitted for the formal parameters to be declared using
interfaces that do not themselves extend the Serializable interface.

Another requirement of RMI is that the published methods of any


remote object must be declared as throwing at least RemoteException.
This covers the eventuality of a networking problem arising.

Essentials of the RMI System 2-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
A Minimal RMI Example – The Server

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

The primary responsibility of the server code is to implement the


behavior that is to be exported over the network. To this end, the class
must implement the interface previously defined. Further, it extends
the base class UnicastRemoteObject. This provides the common
functionality required to export its behavior over the wire. Although
this is a common way to achive this export capability, RMI actually
allows you to achieve this in other ways, because this might be
necessary as a result of the single implementation inheritance rule of
the Java programming language.

The fact that the superclass UnicastRemoteObject has a constructor


that is declared as throwing RemoteException explains why the
constructor for this class is also declared as such. You cannot catch a
superclass constructor exception in a subclass constructor. This is a
language rule that is enforced by the bytecode verifier, and forms part
of the security system for the Java technology platform.

2-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Although the interface declared that the method tellMe might throw
an exception, the implementation might not throw any exceptions, or
even declare them.

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.

Essentials of the RMI System 2-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
A Minimal RMI Example – The Client

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.

When the remote reference is obtained, it is stored in a variable that


has been declared using the interface type created for the server. Using
that variable, you can call the remote method(s) using the same syntax
as for local methods.

2-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

A Minimal RMI Example – Executing

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 registry, by issuing the rmiregistry command.

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.

Essentials of the RMI System 2-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Downloading the Stub

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.

2-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
There are two ways that you can install a security manager. The
simplest from a programmer’s point of view is to use the command
line parameter -Djava.security.manager when launching the client.
However, if this is inconvenient, perhaps from a production point of
view, you can install the security manager in the code. This would
typically be done in the main method that starts the client, using code
similar to the following:
System.setSecurityManager(new SecurityManager());

Essentials of the RMI System 2-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Downloading the Stub – The Client

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.

2-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Downloading the Stub – The Policy File

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.

Essentials of the RMI System 2-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Downloading the Stub – Executing

As with the earlier example in which the stub was immediately


accessible to the server, client, and registry, the first step is to compile
the sources and create the stub class. As before, this is done with the
commands:
javac RMIClient.java RMIServer.java Server.java
rmic RMIServer

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.

2-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Start the rmiregistry by typing the following:
rmid

Essentials of the RMI System 2-23


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Downloading the Stub – Executing

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.

2-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
There is a default security policy file, which is located in the file
jre/lib/security/java.policy under the java installation
directory.

Essentials of the RMI System 2-25


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Agent Example – The Interface

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.

The server must be able to support the submission of jobs that


implement the Runnable interface. To do this, it offers the execute
method. This method accepts the Runnable object as its argument, and
returns the object when the execution is complete. The method must
return the Runnable object after completion, because this is a
convenient way for the results of the job to be passed back to the
client.

2-26 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Agent Example – The Server

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 server implementation is simple. The remote method simply


receives the job using its Runnable argument and executes the
associated run method. After the job completes, the remote method
returns the Runnable object to the client.

Essentials of the RMI System 2-27


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Agent Example – The Agents

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

2-28 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
3 public class RunnableThree implements Runnable, Serializable {
4 private int val1 = 99;
5 private int val2 = 7;
6 private int result;
7
8 public void run() {
9 result = val1 / val2;
10 System.out.println("Calculation shows that " +
11 val1 + " divided by " + val2 +
12 " gives " + result);
13 }
14
15 public String toString() {
16 return "A "RunnableThree" containing " + result;
17 }
18 }
Code 2-11 RunnableThree.java

Essentials of the RMI System 2-29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Agent Example – Agent Client

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

The client in this example is simple, but demonstrates a useful


technique for remote class loading. Instead of using the
java.rmi.server.codebase property to inform remote classes where
to load the agent classes, the client loads the agent from a URL. This is
achieved by the URLClassloader and causes objects created from the
agent classes to be serialized in such a way that they carry the required
information about their origin with them.

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.

2-30 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Agent Example – Deployment Architecture

Figure 2-2 Deployment Architecture of the Agent Example

In the agent example on the preceeding pages, a number of classes are


moved between systems and it is worthwhile to examine these
movements, along with the triggers that cause them.

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.

Essentials of the RMI System 2-31


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
When the server is started, it first registers itself with the
rmiregistry. This involves sending the serialized form of the server’s
own stub to the registry (Step 1 in the diagram). When the registry
receives the serialized stub, it needs the server’s stub class to
deserialize it. For this to work, the server must have correctly
advertised a java.rmi.server.codebase value, and the class must
be available at that URL. The class loading is shown as Step 2.

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.

2-32 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Agent Example – Starting the Server

Running the example requires the correct setup of five components.


These are the server, the client, the rmiregistry, and two web servers.
In fact the two web servers could be one, but the demonstration is
more realistic with two.

The first step on the server machine is to start rmiregistry. Be careful


to do this in such a way that the registry cannot load the server stub
class from its classpath. The command line for this is of this form:
java -jar ${JINI_BASE}/lib/tools.jar -port 8080 -dir share/

In this command line, ${JINI_BASE} is the directory in which the Jini


distribution is installed. The webserver exports files from the directory
specified after the -dir option, in this case a subdirectory called share
under the directory in which the command is executed.

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

Essentials of the RMI System 2-33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
RMI server’s stub class is available from it. You should actually verify
that you can load the stub by pointing a web browser at the URL you
believe should load the class. For example, if you have a stub in a fully
qualified class called server.MyStub, and you are intending to
describe the codebase property as:
http://server.mydom.com:8080/classes/ then you should verify
that attempting to load the URL:
http://server.mydom.com:8080/classes/server/MyStub.class
results in a class file being loaded.

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.

2-34 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2

Agent Example – Running the Client

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.

Essentials of the RMI System 2-35


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Exercise: Deploying A Distributed RMI System

Exercise objective – Demonstrate the use of


java.rmi.server.codebase for the correct deployment of a fully
distributed RMI system.

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.

2-36 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

Essentials of the RMI System 2-37


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Describe the essential features of RMI

❑ State the purpose of the remote interface in an RMI system

❑ List the steps required to build stubs for an RMI system

❑ State the purpose of the rmiregistry

❑ 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

❑ Install and configure the security manager

❑ State the problems that arise if a security manager is not installed


in an RMI system that must download classes

2-38 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
2
Think Beyond

What features do you need to add to the RMI foundation to achieve


the kind of spontaneous networking that was discussed in Module 1?
Are all these facilities achievable on top of pure RMI, or do you need
to add an additional low-level capability?

Essentials of the RMI System 2-39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Investigating Jini Technology 3

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

● State the network assumption that underpins Jini technology

● Distinguish between Jini technology and JavaSpaces technology

● State the meaning of the terms “service,” “service proxy,” and


“federation” in the context of Jini technology

● Describe how Jini services are located using capabilities

● State the software and version requirements for running Jini


technology

● 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

Discussion – There are several parts to Jini technology. Because each


depends upon the others to some extent, you need to gain an
understanding of the overall system, and the way the pieces fit
together, before you can effectively investigate the details of each part.

3-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

What Is Jini Technology?

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."

Investigating Jini Technology 3-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Federation implies a loose coordination between the parts. In this case
it means that services can be added to and removed from a network
freely. If a service is present, it is available for use by any interested
parties. However, if the service goes away unexpectedly, this does not
cause catastrophic failure in the other clients, instead it removes the
ability to use that service.

Building these types of federations requires predefined protocols.


These protocols must be clear enough to allow services to be
interpreted and flexible enough to allow for operation where services
are written independently. This is achieved largely through the use of
class names and interfaces.

You can locate services by looking them up in a special service called


the Lookup service. To identify a particular service, you do not need
its name. Instead, you identify the interface or interfaces that the
desired service must implement. In effect, rather than asking for a
service by name, you ask for it by capability. This significantly reduces
the administration load, because it is no longer necessary to specify
network resources by name or hostname.

The network connections between service proxies and their supporting


services can be handled in any way that is convenient to the service.
Jini technology does not require that you use RMI. In fact, you can use
any protocol, provided that it can be programmed in the Java
programming language. You must use the Java programming
language because this is the only way that the code can reliably be
loaded into systems that have not been preconfigured with the
executable code.

3-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Example Services

You can encapsulate almost any piece of software as a Jini technology


service. The important point is to think in terms of an interface that
describes the functionality that is offered. As much as possible, this
interface should be agreed upon with all organizations that are likely
to be interested in services of the type.

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.

A printer is a common example service. In this case, the core interface


should define a print method with an appropriate argument. This
argument might be a string, or it might be an input stream. The idea
would be that the input stream allows the service to read the data to
print at will, rather than have the entire print job sent over the
network as the argument to the remote method call.

Investigating Jini Technology 3-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Another example service is a Lookup service. This would be used by
both clients, to locate a service, and by servers to register themselves.
In the case of a service registering itself, the service must be passed as
an argument to the registration call.

3-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Supporting Jini Technology

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.

Investigating Jini Technology 3-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
In addition to an appropriate revision of the Java technology platform,
you must also provide a Hyper Text Transfer Protocol (HTTP) server.
This HTTP server is used to provide classes for loading across the
network. You can use any URL protocol for classloading provided it is
supported by all clients. Because of this support issue, HTTP is the
most commonly used protocol.

3-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Components of Jini Technology

There are three key parts to Jini technology:

● The programming model

● Services

● A powerful and flexible Lookup service

The programming model, which is the subject of the next two


overheads, defines and supports an approach to distributed
computing that takes into account the unique nature of a network
when compared with a standalone computer system. The
programming model defines APIs, which can be used either
individually or in concert when building any distributed Java
technology system, regardless of whether it is viewed as a Jini
technology system.

Investigating Jini Technology 3-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Although services are fundamental to the concept of Jini technology,
only Sun Microsystems™ implementation of the Lookup service is
provided with the base distribution of Jini technology. Additionally,
the JavaSpaces™ service is often used with Jini systems. However, it is
expected that numerous services will be provided by third parties, and
that much of your programming with Jini technology will involve the
creation of new services.

In addition to being a Jini technology service, the Lookup service is


also a fundamental part of Jini technology. It is the one part that is
uniquely Jini technology. You can use the programming model, or the
JavaSpaces service, in a distributed Java technology system without
that system necessarily being viewed as Jini technology. The Lookup
service is responsible for the spontaneity associated with Jini
technology. Whenever you add new services to the network, those
services register with the Lookup service. Registration makes a service
visible to interested clients. The Lookup service can actively notify
clients that the new service is now available. Similarly, when a service
ceases to be available, it is removed from the Lookup service, and the
Lookup service can notify interested clients that this has happened.

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.

3-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Jini Programming Model

There are three primary parts to the Jini technology programming


model:

● 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.

You can use leases, distributed events, and transactions either


individually or together to assist in building any distributed Java
technology system. You can use these features as extension APIs for
the RMI programming model.

Investigating Jini Technology 3-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
When you obtain the Jini software distribution, for example, by
downloading it from the Java Developer Connection (JDC) web site, it
contains APIs for these three aspects of the programming model. The
primary definition of these APIs is through interfaces; however, in
addition to these interfaces, you will find sample implementations that
you can use immediately.

3-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Programming Model Assumption

The Jini technology programming model is based on a fundamental


assumption about the nature of large distributed systems. The
assumption is that networks are inherently unreliable.

This might seem surprising to you; you are probably accustomed to


working in a networked environment and suffering a network failure
only on rare occasions. However, in a typical working environment,
you are not really dealing with a large distributed system. Rather you
are dealing with two systems and a stretch of cable between them. One
system is your desktop machine, the other is a server.

The unreliability becomes apparent as the distributed system expands


to dozens or hundreds of machines, perhaps separated by large
geographical distances. Failures can be caused by a variety of reasons,
even in the absence of actual electronic fault. For example, a system
can be brought down for maintenance, or simply turned off without
warning. Perhaps warning was given, but not to all the affected
parties.

Investigating Jini Technology 3-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
An important feature of systems with a large number of nodes is that
as the node count increases, the overall reliability of the system
decreases. At some point, the probability of all parts of the entire
system working at the same time begins to approach zero, even if the
elements are individually very reliable.

3-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Leasing Overview

Leasing is about distributed resource management and garbage


collection. In a distributed system, a server that provides some
resource needs to know if clients are using that resource. If they are,
then the server must maintain, and perhaps update, the resource. If, on
the other hand, the clients are no longer using the resource, then the
server needs to know this so that it can recover the resource for future
use.

The leasing mechanism supports this concept by requiring that the


client, when it has obtained a resource, must notify the server at
intervals that it is still using the resource. If the client should fail, it
will fail to renew its lease on the resource. The server can eventually
reclaim the resource despite the client never having formally released
it.

Investigating Jini Technology 3-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
The leasing mechanism does not preclude all possibility of resource
leaks. In the same way that the garbage collection mechanism built
into Java technology is susceptible to leaks through poor
programming, you can program a client that mindlessly renews leases
of resources that it no longer needs. However, dealing with this type of
mistake is not the goal of leases. Leases are designed to deal with
problems that arise because of the unreliable nature of the network. In
this context, leases are highly effective.

3-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Distributed Events 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.

Investigating Jini Technology 3-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
The second problem with standard events is that they do not support
leases. When a listener registers to receive events from an event
source, a certain amount of resource is used in the event source.
Memory is required to keep track of the listener, and CPU time must
be used to dispatch events to each listener. To avoid these problems,
the event registration should be leased. That is, the listener should
from time to time notify the event source that it is still alive, and is still
interested in receiving the events it originally requested.

You can summarize this information as follows: JDK 1.1 events do not
support unreliable networks.

3-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Jini Technology Transactions

Jini technology transactions are similar in concept to database


transactions. Fundamentally, they provide a way of grouping a set of
operations in such a way that either the entire set of operations
succeeds, or none of them have any long-term effect. The central point
here is that sometimes a group of operations are required to achieve a
certain effect and if any one of them should fail, the entire effect is
spoiled.

To handle the possibility of a failure in a set of operations, you should


perform each operation in such a way that it can be undone and that
you are aware of the success or failure of each operation. As soon as
any operation fails, the whole set must be undone.

In typical database management systems, you have a specified, fully


functional, transaction system. However, in Jini technology, in addition
to a basic transaction mechanism, there is also a framework specifying
the API by which you can handle transactions, and allow for the
implementation of new transaction schemes that are appropriate to an

Investigating Jini Technology 3-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
individual service. The transaction mechanism is somewhat less
functional than its counterpart in databases, and the exact semantics of
what transactions mean can vary between different Jini services.

3-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Overview of Lookup and Discovery Protocols

Jini Lookup and Discovery protocols are used to locate Jini Technology
Lookup services and find entries within them.

When a service is connected to a network, before it can register, it must


first find one or more Lookup services. This process of finding a
Lookup service is called Discovery and can be done either in a directed
or a broadcast fashion.

When a client is connected to a network, before it can use the services


available on that network, it must first find one or more Lookup
services. This aspect is the same as that performed by a service that
wants to register with a Lookup service. For the client, after a Lookup
service has been located, the next step is to obtain a list or partial list of
the services registered with that registrar. This process is called Lookup.
You will see later that there are close parallels between the read
methods in the JavaSpace interface and looking up a service in a
registrar. In both cases you describe the aspects of the entry you are
looking for, and the service attempts to return an item that matches
your request. However, a registrar is different from a space. These
differences are described in later modules.

Investigating Jini Technology 3-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
You can duplicate Lookup services on the local network, and this
duplication constitutes replication, which can increase overall
reliability for a distributed system.

Similar to other Jini technology services, such as JavaSpaces


technology, a Lookup service can send remote events to interested
parties when new services are registered. In fact, the registrar can
notify the system when a service is removed. This notification feature
forms the cornerstone of spontaneous networking, and as such, places
the registrar at the heart of Jini technology.

3-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Overview of JavaSpaces Technology

In the context of Jini technology, JavaSpaces technology software is a


service. JavaSpaces technology is not part of the Jini technology
distribution, but is available separately.

The primary function of a space is a shared memory mechanism that


enables some elegant and expressive distributed protocols. You can
use JavaSpaces services to store any object that implements the Entry
interface and adheres to a small set of rules.

The programming API of the JavaSpaces software is simple, although


this belies the fact that programming with it differs substantially from
more familiar storage systems. The JavaSpaces software provides four
fundamental operations: read, take, write, and notify.

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.

Investigating Jini Technology 3-23


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
The take operation is similar to a read operation except that if a
match is found, it is removed from the space as it is returned to the
caller.

A write operation, as the name suggests, is used to place an entry into


the space.

The notify operation is used to request that an event be sent to the


caller when an entry that matches a given template is written into the
space.

3-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Running the Distribution Software

The distribution software includes a number of services that you


normally want to run when you are testing your own code. The first
two are not really specific to Jini technology, they are: a cut-down web
server intended for distributing classes, and the RMI activation
daemon.

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.

Investigating Jini Technology 3-25


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Running the Distribution Software

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 \

3-26 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
36 ${JINI_BASE}/lib/transient-outrigger.jar \
37 ${SPACE_GROUP} &
Code 3-1 RunAll

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.

In the previous example, a short delay is introduced after starting


rmid. This is done because some of the services will fail in their
initialization phase if the rmid is not already running and accepting
registration requests.

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.

When starting the Lookup service, you must specify the


java.rmi.server.codebase value as a command-line argument.
This is then set inside the program itself. The other arguments are the
security policy file (the code installs the security manager) a log file
name, and a list of groups for which this Lookup service is intended to
provide service.

Investigating Jini Technology 3-27


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
To start the transaction service, you must supply the policy file both as
a property, and as a command-line argument. This might change in
future versions of the service. The jar file containing the transaction
service is called mahalo.jar. The transaction service also requires that
you specify the codebase value from which you can load its stubs and
other classes, a log file, and a group name. The transaction manager
binds only to the Lookup services advertising for that group.

The JavaSpaces technology service has a slightly different approach to


its command-line arguments. Both the codebase and policy file are
specified using property specifications in the conventional way. The
only argument to the command line is the group that the space tries to
join.

3-28 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Running the Services Browser

In a development environment, you often want to run the services


browser. This tool monitors the Lookup services and displays them,
along with the services that are registered in them. This is a valuable
debugging tool that allows you to determine if your Lookup service is
running, and if your service has successfully registered. This enables
you to distinguish between service provider problems and service
client problems.
1 #!/usr/bin/ksh
2
3 JINI_BASE=/home/simonr/jini1_0
4 WEB_HOST=proto198
5 WEB_PORT=8080
6 CLASS_PATH=${JINI_BASE}/lib/jini-examples.jar
7 SECURITY=-Djava.security.policy=${JINI_BASE}/example/browser/policy
8 CODEBASE=http://${WEB_HOST}:${WEB_PORT}/jini-examples-dl.jar
9 CB=-Djava.rmi.server.codebase=${CODEBASE}
10 EXEC_CLASS=com.sun.jini.example.browser.Browser
11
12 java -cp ${CLASS_PATH} ${SECURITY} ${CB} ${EXEC_CLASS}
Code 3-2 RunBrow

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.

Investigating Jini Technology 3-29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Running the Services Browser

When the browser starts up, the following window is displayed:

Figure 3-1 Services Browser Initial Window

3-30 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
If your network does not support multicast, or if the Lookup service
you wish to browse is located remotely enough that multicast does not
reach it, then you can use the directed lookup mechanism. To do this,
select the menu options File and Find One. The following window is
displayed:

Figure 3-2 Directed Lookup Service Prompt

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 ":".

Investigating Jini Technology 3-31


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3

Running the Services Browser

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.

3-32 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Figure 3-5 illustrates the services list shown in the menu:

Figure 3-3 Services List in the Services Browser Menu

Investigating Jini Technology 3-33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Exercise: Running the Jini Services and Browser

Exercise objective – Run the services provided with the Jini


technology distribution, and demonstrate the use of the browser.

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.

3-34 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

Investigating Jini Technology 3-35


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Check Your Progress

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

❑ State the network assumption that underpins Jini technology

❑ Distinguish between Jini technology and JavaSpaces technology

❑ State the meaning of the terms “service,” “service proxy,” and


“federation” in the context of Jini technology

❑ Describe how Jini services are located using capabilities

❑ State the software and version requirements for running Jini


technology

❑ 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-36 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
3
Think Beyond

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?

● How do you achieve this?

● How would you provide the required configuration information?

● How would you handle the timing issues?

● How would you handle the security specifications?

● Are there any web servers already in place that could be used to
provide the classes?

● Are there company security policies and/or procedures that might


need to be considered?

Investigating Jini Technology 3-37


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Leases 4

Objectives
Upon completion of this module, you should be able to:

● Describe the purpose of leasing

● Distinguish between lease grantors and lease holders

● State the possible characteristics of leases, and the distinction


between duration and absolute expiry time

● Describe typical lease scenarios, and the flow of control and data
that occurs in them

● Write client code using the key leasing APIs

● Write server code using the Landlord lease APIs

4-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Relevance

Discussion – Leasing is crucial to the management of distributed


resources. What consequences can you imagine of either badly
implemented leasing strategies, or the absence of leases?

4-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

Jini Distributed Leasing Terminology

To understand leases you need to learn some terminology. The


supplier of a resource is usually the supplier of a lease for that
resource, and is normally referred to as the lease grantor. On the other
hand, the party to which the resource is leased is normally referred to
as the lease holder.

Requests for a lease, or grants of a lease, are for a certain amount of


time. This time is normally expressed as an absolute time at which the
lease is expected to expire. This time is specified in milliseconds since
the "epoch" – that is, January 1, 1970. When you renew a lease, you
typically specify the additional time (in milliseconds) for which you
would like the lease.

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?

A lease is a notification from one party (the lease holder) to another


party (the lease grantor) that the lease holder is interested in the
resource to which the lease applies.

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.

4-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

Why Leasing?

Granting a lease to the user of a distributed resource allows the


resource owner to determine if the resource is no longer required, and
reclaim it, even in the event of partial or complete network failure.
This is one fundamental concept behind distributed garbage collection.

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.

4-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

Characteristics of the Lease

As a client, when you request a resource, you generally provide an


argument that indicates for how long you want the resource. However,
the server might not grant you the resource for the duration for which
you have asked. In this case, one of two things might happen; you
might be granted the resource with a shorter lease or your request
might be denied outright.

If the lease is denied, indicating that the resource is unavailable, then


the request method throws a LeaseDeniedException. If a lease
request is denied, you can try again later; if that resource becomes
available, your subsequent attempt might succeed.

If a shorter lease is granted, you can attempt to renew that lease at


intervals. However, you should be aware that your renewal request
might be denied.

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.

4-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

Lease Flow – 1

This section describes the flow of operations around the system as


leases are created, used, and expire.

The client makes a request of a server to use a resource. If the resource


is granted, a lease is associated with the resource for that client. From
this point, the client and the server take notice of the lease.

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.

A client receiving a lease keeps track of the anticipated expiry time of


that lease.

If a client has finished with a resource, it should cancel the lease


explicitly to allow the server to reclaim it.

Leases 4-9
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

Lease Flow – 2

If a client is still using a resource when the associated lease is nearing


expiry, the client should try to renew the lease. This attempt might be
denied, in which case you should make a subsequent renewal attempt
for shorter additional time.

It is interesting to consider exactly how long before a lease expiry is


due to occur that you should try to renew that lease. Keep in mind that
a renewal request must pass over the network. Because of this, it
cannot be considered to be instantaneous, and an attempt to renew a
lease a few microseconds before it expires is unlikely to reach the
server in time. On the other hand, renewing leases that have several
minutes to run risks increasing network traffic unnecessarily. The cost
in terms of time of allowing a lease to expire accidentally (wasting the
work in progress that depends on that lease) is probably greater than
the cost of a few additional renewals.

4-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
At the server, when the lease expires, the associated resource can be
considered eligible for reclamation. This might mean that the resource
is actually deleted and its memory reclaimed by garbage collection, or
it might simply be added to the resources made available for use by
other clients. The precise semantics of an expiring lease are dependent
on the particular resource that granted the lease.

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.

Figure 4-1 Simple Lease Flow

4-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Lease Flow With LeaseRenewalManager

The LeaseRenewalManager class enables a client to have a lease, or


leases, renewed regularly with little programmer effort. Internally, the
LeaseRenewalManager keeps track of lease time-outs. The
LeaseRenewalManager tries to renew any leases that are
approaching expiry.

The LeaseRenewalManager class can also cancel individual leases,


remove leases from management, and indicate that a lease is required
until a particular time.

Figure 4-2 Lease Flow with a LeaseRenewalManager

Leases 4-13
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

The Lease Interface

Individual servers are free to implement leasing according to whatever


policy is appropriate for the resources they provide. However, to
ensure interoperability, some standard description of the interface of a
lease must be defined. In Jini technology, this is done by the interface
net.jini.core.lease.Lease. The three most important methods
defined in this interface are:
long getExpiration()
void cancel()
void renew(long duration)

The function of these methods is largely self evident. The


getExpiration method returns the value that represents the number
of milliseconds after January 1, 1970 that the lease will expire.

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.

4-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
When you renew a lease, you specify the new time that you require in
milliseconds. The existing lease is replaced by the newer one.

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

You can manipulate individual leases that are managed by a


LeaseRenewalManager using the methods of the
LeaseRenewalManager class.

You use renewFor and renewUntil methods to add a lease to the


renewal manager, and indicate that the lease should continue to be
renewed for a duration or up to an absolute point in time. In either
case, you can specify a listener that will be notified if the manager fails
to maintain a lease as requested.

The setExpiration method allows you to modify the point at which


you no longer expect to need a resource. In this case, the lease should
already be in the managed set.

4-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
The cancel method causes a specified lease to be cancelled forthwith.
The lease is then removed from the managed set. Somewhat similar is
the remove method, which removes the lease from the managed set,
but does not actively cancel it. The clear method removes all leases
from the managed set without actively cancelling them.

Using the LeaseRenewalManager removes the burden of renewing


leases from you, and the overall distributed system still gets the main
benefit of leasing; that is, if your client fails, the resource is recovered
eventually. However, you must ensure that if you no longer need the
resource, you inform the LeaseRenewalManager. Otherwise, you
might find that your lease is being renewed indefinitely, to the
detriment of the server and other parts of the system.

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.

A LeaseDeniedException indicates that a specified lease time that


accompanies a resource request was too long, and has been rejected
outright. Alternatively, it could mean that a resource is unavailable.
The exact cause of this exception depends on the implementation.

An UnknownLeaseException might arise when you try to perform


operations on a lease that has already expired. Remember that lease
expiry is controlled by the server, and its clock might be slightly
different from your own. Also, it is possible, when attempting to
renew a lease that is near expiry, that the round-trip time to make the
renewal request takes long enough for the lease to have expired in the
meantime.

4-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4

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.

While this approach seems easy to implement, it is also inefficient.


RMI remote object/stub pairs involve network overheads, and should
not be created freely without a good reason. The is an alternative
approach, and because of this, support classes are provided that
facilitate consistent implementations of this alternative approach,
which is described on the following pages.

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.

4-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Landlord Lease Classes

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.

Figure 4-3 Diagram of Landlord Leases

The LandlordLease and the cookie must both implement the


Serializable interface, because they are passed over the network. In
addition, the Landlord object must present a remote interface.

The LandlordLease class includes a static inner class called


LandlordLeaseFactory. This class provides a convenient mechanism
for creating LandlordLease objects that are added to the appropriate
Landlord.

Leases 4-21
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Exercise: Investigating Leasing

Exercise objective – Create a leases client and investigate the behavior


of a lease when the lease times out, is renewed, or is cancelled.

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.

4-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● 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 the purpose of leasing

❑ Distinguish between lease grantors and lease holders

❑ State the possible characteristics of leases, and the distinction


between duration and absolute expiry time

❑ Describe typical lease scenarios, and the flow of control and data
that occurs in them

❑ Write client code using the key leasing APIs

❑ Write server code using the Landlord lease APIs

4-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
4
Think Beyond

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:

● Outline the distinctions between distributed and local event


delivery

● State the reasons for the special aspects of distributed events

● Outline two alternative ways of handling events, and state the


relative benefits of each

● State at least two uses for the handback object

● Write code to register for, and receive, distributed events from an


event source

● Write code to issue distributed events

5-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Relevance

Discussion – Asynchronous notification of a situation that arises on


one system to other interested parties is an important part of many
distributed systems. In Jini technology, it is fundamental to the
spontaneity aspect of the system. What features of the JavaBeans™
event model are appropriate to use over a distributed system, and
what features are inappropriate? How could you modify the model to
support widely distributed event delivery?

5-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Comparing Local and Distributed Events

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.

By contrast, event delivery between systems in a distributed


environment is much less certain. Events can be lost completely, and
the order of event reception differs from the order of generation.
Distributed events in Jini technology cannot hide these realities, so
instead, they are designed to operate in a way that makes it possible to
create a correct and reliable program despite these risks.

Distributed Events 5-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

What Are Distributed Events?

The distributed event model in Jini technology is an extension of the


JDK 1.1 event model. The events it uses are subclasses of the
java.util.EventObject class. In this way, compatibility is
maintained with the existing event model.

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.

To support unreliable networks, listener registration in a distributed


system is handled on a leased basis. That is, when a listener registers
to receive events, the source of events continues to supply those events
for a certain period of time unless the listener renews the lease that is
returned with the event registration. This enables the event
registration to be canceled automatically when the lease expires,
allowing deregistration of the listener even if the listener fails.

5-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Because events in a distributed environment might arrive in an order
different from the one in which they were issued, or be duplicated,
distributed events in Jini technology carry a sequence number. This
allows the recipient to determine if the order of two events has
changed, and if events disappear completely, it can determine when
subsequent ones are received. In addition, the recipient can use the
sequence number to identify old events, repeated events, or both.

The distributed event registration mechanism uses a standard listener


type for all kinds of events. This is the
net.jini.core.event.RemoteEventListener. A single method,
notify, is declared by this interface, which means that some
mechanism is required to allow the listener to distinguish between
different events sources that call the same handler method. This is
addressed by allocating a unique identifier to each event registration.
In this way, when the notify method is invoked, it is a simple matter
of checking the event ID to determine the reason for this event.

Distributed Events 5-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Event Registration (Typical)

Under typical circumstances, event registration requires three


arguments. The first argument is an RMI remote reference to the
listener itself. The event source uses this to invoke the notify method
when events arise.

The second argument is normally an indication of how long the


registration is required. This is the lease request.

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.

5-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
After a listener has submitted a registration call, the event source
returns information that describes the registration. Although it is not
required that event sources use it, the class
net.jini.core.event.EventRegistration is intended for this
purpose. There are four fields in this class. The first field is the event
ID. The event ID field is a number that is stamped on each event that
is issued as a result of this registration. It is unique for the event
source, so that the combination of event ID and the second field, the
source field can be used to uniquely identify the registration from
which any particular event resulted.

The third field of an EventRegistration object is the lease that has


been granted on the registration. If you decide that you no longer need
to receive events before the lease has expired, cancel the lease. If you
want to continue to receive events after the lease has expired, renew it
soon enough to be sure that the lease does not expire before the
renewal completes.

The fourth field, sequence number, indicates the starting sequence


number that events from this registration carry. Sequence numbers
should not be reused by the server, and should always increase. It is
ideal, but not required, that sequence numbers increase monotonically.
In general, the only situation in which a non-monotonic increase
should arise is if the server crashes and then recovers.

Distributed Events 5-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Dispatching Events

An event is dispatched by the server calling the notify methods of


each registered listener. The notify methods are invoked using RMI,
because they are remote methods. That is, the listener itself is a remote
object.

Dispatching events remotely is synchronous. This means that you


should implement notify methods to return quickly; otherwise the
overall system responsiveness will suffer. If necessary, you can do this
by using threads.

The RemoteEvent object that is passed as the argument to the


listener’s notify method contains four fields. The event ID field and
source field enable you to determine exactly which registration caused
this event to be issued.

5-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
The sequence number field enables you to determine if this is either a
duplicate or an out-of-sequence event. If the server issuing the event
guarantees monotonically increasing sequence numbers, you can use
the sequence number field to determine if any events have been lost or
delayed.

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.

In fact, there is no requirement that prevents the registration of a


listener by code other than the listener’s own code. If you use this
approach, which is commonly referred to as third party event handling,
it can simplify the listener’s job if it is passed an object from the
registering party as part of the event. The marshalled object can be any
serialized object, so it can contain simple data fields or be more
complex. For example, if an RMI stub is placed in the marshalled
object field, a flexible distribution technique becomes possible by
having the third party forward the events by calling the
notify(RemoteEvent) method of the stub that is in the marshalled
object.

Distributed Events 5-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Figure 5-1 Typical Event Registration and Delivery

Simple Distributed Event Flow

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.

5-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Third-Party Event Handling

Although you can issue event registrations in the form of "tell me


when something happens," you can also request that the event be
dispatched to a third party. This is like saying "tell her when
something happens." You do this by passing a reference to the
required listener, instead of to "this," to the registration call.

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.

Distributed Events 5-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
It might be that many listeners need to register for events, but each
listener is really interested only in a few of the events. Under these
conditions, having all events sent to all listeners involves a great deal
of redundant network traffic. However, if you create an intermediate
event handler that can receive all the events, it can conditionally
forward them to the main listeners as needed. This works well if the
handback object is an RMI remote reference to the real listener. If the
third party is near to the event source (in terms of network topology
and bandwidth), this approach can result in improved overall
throughput.

5-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

Figure 5-2 Typical Third-Party Event Registration and Dispatch

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.

In a more complex variation, the handback object could be a


composite, containing both a remote reference to the real client and a
filter class that determines if the event is to be forwarded. This allows
runtime control of the filtering, and is therefore more flexible than
hard coding the filtration into the third party.

Distributed Events 5-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5

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.

The RemoteEventListener interface declares only one method; that


is, the notify method. This method receives events from event
sources, and is the signature method of a remote event listener. The
method is declared as it throws a RemoteException, to support the
fact that this method must be implemented as a remote method.

The UnknownEventException can also be thrown by the notify


method of the RemoteEventListener. This might occur if the
listener has cancelled its registration or allowed its lease to expire. This
can also happen if a listener receives an event for which it does not
believe it is registered. When a notify method throws this exception,
the source of the event should update its registration records,
removing the entry that caused the exception.

5-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Exercise: Remote Event Listener

Exercise objective – Create a listener for remote events.

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.

Distributed Events 5-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

5-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Outline the distinctions between distributed and local event


delivery

❑ State the reasons for the special aspects of distributed events.

❑ Outline two alternative ways of handling events, and state the


relative benefits of each.

❑ State at least two uses for the handback object

❑ Write code to register for, and receive, distributed events from an


event source

❑ Write code to issue distributed events.

Distributed Events 5-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
5
Think Beyond

● What happens if a listener is killed, or goes temporarily off line?

● How could you implement "third party" event handling?

● What benefits would accrue if you could use a a custom written


third party? Or using the handback object to control the behavior
of the third party?

● How could you control filtering by the third party?

5-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Lookup and Discovery 6

Objectives
Upon completion of this module, you should be able to:

● State the software and network requirements for running Jini


technology Lookup services.

● State what aspect of spontaneous networking is not addressed by


Jini technology.

● State the purpose and benefits of Multicast Discovery, Multicast


Announcement, and Unicast Discovery protocols.

● Write code using the Jini technology distribution classes to use the
Discovery and Announcement protocols.

● Write code using the ServiceRegistrar and supporting classes


to use the facilities of a Jini technology Lookup service both as a
client and as a service provider

● Distinguish between core and non-core Jini technology


distribution classes

● Write code to implement a simple Jini service and apply attributes


to that service

● Use the transient keyword in conjunction with accessory methods


to handle non-serializable elements of a service class.

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.

6-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Roles of the Lookup and Discovery Protocols

The Lookup service describes the protocols used to register services


with a registrar, and to locate the services that have been registered.

The package net.jini.core.lookup contains most of the classes that


support programming with the lookup protocols. One particularly
useful class, the JoinManager, is located in the package
com.sun.jini.lookup. The package net.jini.lookup contains a
management interface that is beyond the scope of this class.

Lookup and Discovery 6-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The Discovery service describes the protocols used to locate specific
Jini technology Lookup services.

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.

6-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Discovery Protocol Software Requirements

The Discovery protocols make certain requirements of the virtual


machine and underlying operating system.

Jini technology is founded on the RMI system, including extensions to


RMI that were introduced with the release of JDK 1.2.

Jini software requires JDK 1.2. Specifically, it requires the extended


RMI facilities just mentioned, and the weak reference services that
were introduced into the core at this revision.

In a Jini technology system, even more so than in systems using RMI,


classes move from one machine to another. For this to happen, those
classes must be available from a reachable URL using a protocol that is
understood by all JVMs that need to download these classes.
Therefore, a functional Jini technology system requires at least one
appropriate server. It is common for an HTTP server to provide for
this requirement. It is not necessary for a server to be running on every
system that hosts Jini technology. Rather, it is more likely that one
server will provide classes to a group of other systems.

Lookup and Discovery 6-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Discovery Protocol Network Requirements

In addition to requirements placed on the JVM, Jini technology also


makes demands of the underlying network system.

Jini technology requires a working network system, but does not


specifically require TCP/IP. The network must be able to support
directed point-to-point messages using a 32-bit addressing scheme and
16-bit “port” numbers. It must also support group messages
(multicast), and be integrated into the JVM. If these requirements are
met, then Jini technology can work equally well with other networks.

It is a fairly self-evident network requirement that every host must


have a unique address. In traditional network systems, this has been
achieved by static configuration, usually performed by a system
administrator. In a dynamic environment, such as those using Jini
technology, devices come and go frequently. To allow this, some kind
of dynamic address allocation scheme is required. Dynamic Host
Configuration Protocol (DHCP) is a common way to achieve this, but
it is neither required nor part of the Jini technology specifications.

6-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Point-to-point messages in a TCP/IP network are generally carried by
the TCP protocol. RMI method invocation uses point-to-point
messaging, which is therefore required for the support of Jini
technology.

When messages need to be sent to multiple recipients, three


approaches are possible. First, the sender can send one point-to-point
message to every recipient. This wastes the sender’s time and network
bandwidth. The second approach is to use broadcasting. This
technique requires that the sender send only one message, thereby
reducing the load on the sender and the network bandwidth
requirements. However, the message goes to all systems on the local
network, regardless of whether they were interested in the message.
The third, and preferred, technique is called multicasting. Multicasting
allows a single message to be sent to more than one recipient, but the
message is received only by systems that have previously expressed an
interest in the messages. Jini technology uses multicasting to support
the Discovery protocols. However, in an environment that does not
support multicasting, Jini technology can still operate on a point-to-
point communication basis, although this loses some of the flexibility
of the registrar function.

Lookup and Discovery 6-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Unicast Discovery Protocol

The Unicast Discovery Protocol is used to locate specific registrars.


You must know the network address and port number for the
registrar. There is a convention for specifying a standard port number
and if this is in use by the relevant registrar, you do not need to
explicitly state it.

Because the Unicast Discovery Protocol connects directly with the


registrar at a specified machine address and port number, it uses
point-to-point messaging, not multicasting.

Unlike multicasting, directed TCP messages are not limited to passing


through a certain maximum number of routers. This means that
Unicast Discovery Protocols can locate registrars anywhere on the
network, regardless of the distance.

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.

6-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
You can use the net.jini.core.discovery.LookupLocator class to
establish contact with a specific registrar, if that registrar is already up
and running. If the required registrar is not running when your
program starts, you can use the
com.sun.jini.discovery.LookupLocatorDiscovery class to locate
specific registrars as they start and stop.

Lookup and Discovery 6-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Multicast Protocols

The Multicast Request Protocol is used to identify registrars running


on machines nearby in the network. This protocol does not require that
you specify machine addresses in advance. Rather, its primary
purpose is to locate systems running registrar services. The term
nearby, in this context, refers to network protocol and router
configuration rather than geographic proximity. In other words, a
registrar in the room next door that is separated from the system by a
router that does not forward multicast packets is considered to be
distant. Conversely, a system on the other side of the planet connected
using less than 15 routers, all of which are configured to forward
multicast packets, is considered to be local.

The 15 router limit is configurable using the


net.jini.discovery.ttl property. Fifteen routers is a lot for most
networks.

Registrars use the Multicast Announcement Protocol to advertise their


presence. In this way, a new registrar coming online can immediately
advise clients of its presence, without those clients polling on a regular
basis.

6-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The LookupDiscovery class in the package net.jini.discovery
handles the client side of both multicast requests and multicast
announcements. It provides a simple way to connect to local registries.
The LookupDiscovery class uses an event mechanism to notify the
system of changes in the set of registrars that are known to it. These
DiscoveryEvent objects are sent to registered DiscoveryListeners
using the standard event mechanism. The DiscoveryEvent and
DiscoveryListener classes, such as the LookupDiscovery class, are
members of the net.jini.discovery package.

Lookup and Discovery 6-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

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.

The service must be requested using a template that describes the


interfaces that the required service must implement and attributes that
might be required. Using this approach, you can write lookup code
that behaves in a similar fashion to the rmiregistry, providing the
static location of a service that is registered on a known machine. The
next few slides describe this in detail.

The format of a URL that describes the location of a Lookup service is


essentially the same as any other URL but uses “jini” as the protocol
name and has no directory or filename part.

6-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Example One: The LookupLocator Class

The following is an example of the LookupLocator class.


1 import java.net.MalformedURLException;
2 import java.io.IOException;
3
4 import net.jini.core.discovery.LookupLocator;
5 import net.jini.core.lookup.ServiceRegistrar;
6
7 public class Locate {
8 public static void main(String args[])
9 throws MalformedURLException, IOException,
10 ClassNotFoundException {
11
12 System.setSecurityManager(new SecurityManager());
13 LookupLocator l = new LookupLocator(args[0]);
14 ServiceRegistrar sr = l.getRegistrar();
15 }
16 }
17
18
Code 6-1 Locate.java

This example demonstrates the construction of an instance of the


LookupLocator class, and the method call getRegistrar to obtain a
reference to the specified Lookup service. This is a static technique that
attempts only to connect to the registrar at the time of the call. If the
Lookup service goes down later, no effect is noticed by this program.

If the registrar is not accessible at the time the getRegistrar method


is called, or if the supplied URL is incorrect, an exception is thrown.
Also, this code does nothing with the registrar reference once it has it.
These issues are the subject of the next slides.

Lookup and Discovery 6-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Using a ServiceRegistrar Object

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.

The methods of this interface support three basic operations:


registering a new service; locating a service; and registering to receive
callbacks when a type of service is either added to or removed from
the registrar.

6-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

The ServiceRegistrar Support Classes

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.

Lookup and Discovery 6-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The array of classes argument enables you to specify one or more
classes or interfaces that must appear in the service’s class hierarchy.
To be considered a successful match, the service must have all
specified classes in its class hierarchy and all specified interfaces must
be implemented.

You can use the attribute template specified in the array of entry
objects to further qualify successful matches.

6-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

What Is an Entry Object?

Entry objects are used to describe attributes, such as name, location,


speed, and so on, of services. They are a flexible mechanism.

To be an Entry object, an object must implement the Entry interface


and adhere to certain rules. The Entry interface extends the
java.io.Serializable interface, and it is the serializability of the
entry that is its most significant feature. When Entry objects are
stored, they are generally stored in serialized form.

To support certain operations on Entry objects, you must implement


the equals(Object) and hashCode methods. In most cases, you
can achieve this most easily if you extend the class
net.jini.entry.AbstractEntry.

There are several important requirements that apply to valid Entry


objects, and the fields that compose them. Every Entry must have a
zero argument constructor, and each attribute that is to be stored when
the Entry is placed in the space must be a public, non-transient, non-
final reference to a serializable object.

Lookup and Discovery 6-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Non-static inner classes do not have zero-argument constructors.
Because of this, they are not suitable as Entry classes.

6-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Example of Static Lookup

117 LookupLocator ll = new LookupLocator(args[0]);


118 ServiceRegistrar reg = ll.getRegistrar();
119 Class [] classes = { TransactionManager.class };
120 ServiceTemplate templ = new ServiceTemplate(null, classes, null);
121 TransactionManager mgr = (TransactionManager)(reg.lookup(templ));

Code 6-2 Sample of code from Trans1.java

In the example, the LookupLocator object is created from a specific


URL. The form of this URL is:
jini://host:port/

As usual in URLs, the port number is optional if the service is running


on the default port.

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.

Lookup and Discovery 6-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
To locate the service that you want, you must build an array of the
interfaces that the service should implement. In this example, only one
interface is specified. That interface is the interface of a transaction
manager. This example does not look for specific attributes, nor does it
search for a particular uniquely identified service. Because of this, the
code creates a ServiceTemplate object with the first and third
arguments to the constructor set to null.

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.

ServiceMatches is a container object that aggregates an array of


ServiceItem objects and indicates the total number of matches. This
count is valuable if there are more services than you requested.

6-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Dynamic Location of Lookup Services

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

The LookupLocatorDiscovery class searches for Lookup services that


you tell it about. It does this using the Unicast Discovery Protocol. By
contrast, the LookupDiscovery class searches for any local Lookup
services, using the Multicast Discovery and Announcement Protocols.

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.

Lookup and Discovery 6-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Example: The LookupLocatorDiscovery Class

The following is an example of the LookupLocatorDiscovery class.


1 import java.net.MalformedURLException;
2 import java.rmi.RemoteException;
3 import com.sun.jini.discovery.LookupLocatorDiscovery;
4 import net.jini.discovery.DiscoveryEvent;
5 import net.jini.discovery.DiscoveryListener;
6 import net.jini.core.discovery.LookupLocator;
7 import net.jini.core.lookup.ServiceRegistrar;
8
9 public class Locate1 implements DiscoveryListener {
10 private LookupLocatorDiscovery lld;
11
12 public Locate1(String [] args) throws MalformedURLException {
13 LookupLocator [] locators = null;
14 locators = new LookupLocator[args.length];
15 for (int i = 0; i < locators.length; i++) {
16 locators[i] = new LookupLocator(args[i]);
17 }
18
19 lld = new LookupLocatorDiscovery(locators);
20 lld.addDiscoveryListener(this);
21
22 LookupLocator [] lookups = lld.getDiscoveredLocators();
23 if (lookups.length > 0) {
24 System.out.println("Discovered:");
25 for (int i = 0; i < lookups.length; i++) {
26 System.out.println(lookups[i].toString());
27 }
28 }
29 }
30

6-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
31 private void showRegistrars(ServiceRegistrar [] regs) {
32 for (int i = 0; i < regs.length; i++) {
33 LookupLocator l = null;
34 try {
35 l = regs[i].getLocator();
36
37 System.out.println("Locator: " +
38 l.getHost() + ":" + l.getPort());
39 }
40 catch (RemoteException e) {
41 e.printStackTrace();
42 }
43 }
44 }
45 // PageBreak
46 public void discovered(DiscoveryEvent e) {
47 System.out.println("Discovered:");
48 showRegistrars(e.getRegistrars());
49 }
50
51 public void discarded(DiscoveryEvent e) {
52 System.out.println("Discarded:");
53 showRegistrars(e.getRegistrars());
54 }
55
56 public static void main(String args[])
57 throws MalformedURLException {
58
59 System.setSecurityManager(new SecurityManager());
60 Locate1 l1 = new Locate1(args);

Lookup and Discovery 6-23


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
61 for (;;) {
62 System.out.print(".");
63 System.out.flush();
64 try { Thread.sleep(15000); }
65 catch (InterruptedException e) { }
66 }
67 }
68 }
69
Code 6-3 Locate1.java

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.

6-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Example: The LookupDiscovery Class

The following is an example of the LookupDiscovery class.


1 import java.io.IOException;
2 import net.jini.discovery.LookupDiscovery;
3 import net.jini.discovery.DiscoveryEvent;
4 import net.jini.discovery.DiscoveryListener;
5 import net.jini.core.discovery.LookupLocator;
6 import net.jini.core.lookup.ServiceRegistrar;
7
8 public class Locator implements DiscoveryListener {
9 private LookupDiscovery ld;
10
11 public Locator() throws IOException {
12 ld = new LookupDiscovery(null); // all groups
13 ld.addDiscoveryListener(this);
14 }
15
16 private void showRegistrars(ServiceRegistrar [] regs) {
17 for (int i = 0; i < regs.length; i++) {
18 LookupLocator l = null;
19 try {
20 l = regs[i].getLocator();
21
22 System.out.println("Locator: " +
23 l.getHost() + ":" + l.getPort());
24 }
25 catch (Exception e) {
26 e.printStackTrace();
27 }
28 }
29 }
30
31 public void discovered(DiscoveryEvent e) {
32 System.out.println("Discovered:");
33 showRegistrars(e.getRegistrars());
34 }

Lookup and Discovery 6-25


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
35
36 public void discarded(DiscoveryEvent e) {
37 System.out.println("Discarded:");
38 showRegistrars(e.getRegistrars());
39 }
40
41 public static void main(String args[]) throws IOException {
42 System.setSecurityManager(new java.lang.SecurityManager());
43
44 Locator l1 = new Locator();
45
46 for (;;) {
47 System.out.print("."); System.out.flush();
48 try { Thread.sleep(15000); }
49 catch (InterruptedException ex) { }
50 }
51 }
52 }
53
Code 6-4 Locator.java

This example shows how the LookupDiscovery class provides fully


dynamic networking. It monitors for any Lookup services using the
Multicast Discovery and Multicast Announcement protocols. In most
Jini technology systems, this is the preferred technique for locating
Lookup services.

Note – As with the LookupLocatorDiscovery class, the discarded


method is only called in response to a call to the discard method of
the LookupDiscovery object.

6-26 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Dynamic Service Information

When you have a ServiceRegistrar object, whether statically or


dynamically obtained, you can register to be told about the services
that are registered, or become de-registered, with that lookup service.
This is done using the notify method of the ServiceRegisrar object.

The notify method takes the following five arguments:

● 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.

Lookup and Discovery 6-27


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
If a new service that matches your template is registered, this
corresponds to a TRANSITION_NO_MATCH_MATCH. Similarly, a matching
service that is removed from the Lookup service gives a
TRANSITION_MATCH_NOMATCH.

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.

6-28 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Service Notification Request Example

127 EventRegistration evReg = regs[i].notify(template,


128 ServiceRegistrar.TRANSITION_MATCH_MATCH +
129 ServiceRegistrar.TRANSITION_MATCH_NOMATCH +
130 ServiceRegistrar.TRANSITION_NOMATCH_MATCH,
131 this,
132 new MarshalledObject(regs[i]),
133 Lease.ANY);

Code 6-5 Code fragment from MapAll.java

This example shows an event registration call that requests all


transitions for the provided template. It is taken from the
MapAll.java class.

When a qualifying change occurs in the Lookup service (referred to as


regs[i] in this example) the notify method of the listener (this, in
this example) is called.

Lookup and Discovery 6-29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

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.

The register method takes two arguments. The first is a


ServiceItem object that describes the object that is to be registered.
The second argument is the lease duration that you wish to have on
the storage in the Lookup service.

The returned value from a register method call is an instance of the


ServiceRegistration class. This, and the ServiceItem are
described in detail on the following slides.

In most cases, you should register your service with a number of


Lookup services, and those services might not be continuously
available. To simplify this, you can use the JoinManager class, which
is discussed in detail later in this module.

6-30 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

ServiceRegistrar Support Classes

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.

Lookup and Discovery 6-31


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The Attributes field allows any number of attributes to be specified
when the service is registered.

When searching for a service or requesting notification of a new


service, clients can match any or none of these attributes, as
appropriate.

6-32 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

ServiceRegistrar Support Classes

When you register a service with a registrar using the register


method, the return value is a ServiceRegistration object. This
provides access, using methods, to three essential parts of the
registration information: the allocated ServiceID, the lease, and the
attributes.

The ServiceID is guaranteed to be unique to your service, but should


be common to all registrations of that same service. Therefore, if you
subsequently register the same service with another registrar, you
must use this ServiceID as part of that registration.

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.

Lookup and Discovery 6-33


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The attributes you specified when you register the service are stored
and the ServiceRegistration object provides methods that enable
you to read and modify the attribute values. The mutator methods are
particularly useful because they update the values of attributes
without having to de-register and re-register the service. This is
important with attributes that describe a status rather than static
information. For example, an attribute that indicates whether paper is
available in a printer must be easy to update.

6-34 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

The JoinManager Class

A JoinManager object handles discovery, lookup, and lease


maintenance for clients that register services with registrars.

When registering a service, the first argument required is the service


itself. In addition to the service, you can supply a number of other
arguments when creating a JoinManager object to handle registration
of your service.

In many cases you should provide a set of attributes that describe


aspects of your service. You specify attributes as an array of Entry
instances to the constructor of the JoinManager.

When you attempt to register a service with a registrar, the registration


is not permanent. Rather, you are given a lease on the space allocated
within the registrar. You must update this lease at regular intervals if
the service is to remain in the registrar. The easiest way to do this is
using the class com.sun.jini.lease.LeaseRenewalManager. You
must provide an instance of this class when constructing the

Lookup and Discovery 6-35


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
JoinManager. You can simply create a new instance of the
LeaseRenewalManager class, but if you already have a
LeaseRenewalManager available, you might want to reuse that object.

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.

The JoinManager also provides versions of its constructors that enable


you to specify groups to which the registrar should belong. Make sure
your service is registered with only the appropriate registrars.
Additionally, you can specify LookupLocators to the JoinManager.
This enables you to have your service registered with particular
registrars even if they are not local to the point at which you are
issuing the registration request.

6-36 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Implementing a Service

The following is an example of how to implement a service.


1 import java.awt.Component;
2 import net.jini.core.entry.Entry;
3 import java.io.Serializable;
4
5 public interface CompoundService extends Serializable {
6 public Entry [] getAttributes();
7 public Component getUI();
8 }
9
Code 6-6 CompoundService.java

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.

Lookup and Discovery 6-37


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Attributes for Services

The following are examples of the attributes for a service. Each is


based on the ServiceType class, and provides a name, description,
and type String to help the user identify the service.
1 import java.awt.*;
2 import net.jini.lookup.entry.ServiceType;
3
4 public class EditorServiceType extends ServiceType {
5 public String type = "An Editor";
6
7 public Image getIcon(int type) {
8 return null;
9 }
10
11 public String getDisplayName() {
12 return "Editor";
13 }
14
15 public String getShortDescription() {
16 return "This is a minimal text editing tool";
17 }
18 }
Code 6-7 EditorServiceType.java

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

6-38 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Attributes provide a means for services to communicate more
information to interested clients beyond the interfaces that they
implement. In this example, no dynamic information is provided, but
instead basic name information is provided using the ServiceType
class.

The ServiceType class provides a basic set of attributes with “well-


known” meaning. Another class, ServiceInfo, provides a comparable
group of predefined attributes.

Lookup and Discovery 6-39


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Example Service

The following is an example of using the example service.


1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import net.jini.core.entry.Entry;
5 import com.sun.jini.lease.LeaseRenewalManager;
6
7 public class Service1
8 implements CompoundService, ActionListener {
9
10 // GUI parts are transient
11 private transient JApplet applet;
12 private transient JButton button;
13 private transient JLabel label;
14
15 // but data is serialized
16 private int count;
17
18 public Entry [] getAttributes() {
19 Entry [] attrs = {
20 new MyServiceType()
21 };
22 return attrs;
23 }
24
25 public Component getUI() {
26 if (applet == null) {
27 applet = new JApplet();
28 Container c = applet.getContentPane();
29 c.setLayout(new BorderLayout());
30
31 button = new JButton("Press Here");
32 button.addActionListener(this);
33 c.add(button, BorderLayout.NORTH);
34
35 label = new JLabel("Click Count is " + count);
36 c.add(label, BorderLayout.SOUTH);

6-40 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
37 }
38 return applet;
39 }
40
41 public void actionPerformed(ActionEvent ev) {
42 count++;
43 label.setText("Click Count is " + count);
44 }
45 }
46
Code 6-9 Service1.java

The example service is simple. The most significant feature of this


example is how it handles the user interface. In general, you cannot
serialize AWT components. To handle this, you must arrange to
reconstruct the GUI when the client requests it. Here, you can see that
the GUI components are deliberately marked as transient, so no
attempt is made to serialize them. When the client calls getUI, a new
component hierarchy is built and returned to the caller. You can apply
this technique to a variety of situations where serializing parts of a
service proxy might be impossible or inefficient.

Although the job performed by this service is trivial; all it does is


count the clicks it receives at the client, and updates the display. You
should recognize that, although service proxies commonly do connect
back to their originating machine, there is no requirement for this to be
the case.

Lookup and Discovery 6-41


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Using the JoinManager Class

The following is an example of using the JoinManager class.


1 import java.awt.Image;
2 import java.io.*;
3 import java.net.*;
4 import java.util.*;
5 import java.rmi.*;
6 import net.jini.core.entry.*;
7 import net.jini.core.discovery.*;
8 import net.jini.core.lookup.*;
9 import net.jini.entry.*;
10 import com.sun.jini.lookup.*;
11 import com.sun.jini.lease.*;
12 import net.jini.lookup.entry.ServiceType;
13
14 public class Joiner {
15
16 private static class Listen implements ServiceIDListener {
17 private JoinManager jm = null;
18
19 public void serviceIDNotify(ServiceID sid) {
20 System.out.println("service id given: " + sid);
21 if (jm != null) {
22 showRegs();
23 }
24 }
25
26 public void setJoinManager(JoinManager jm) {
27 this.jm = jm;
28 showRegs();
29 }
30 // PageBreak
31 private void showRegs() {
32
33 ServiceRegistrar [] regs = jm.getJoinSet();
34 System.out.println("Join set of " + regs.length + " contains:");
35 for (int i = 0; i < regs.length; i++) {

6-42 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
36 try {
37 LookupLocator ll = regs[i].getLocator();
38 String host = ll.getHost();
39 try {
40 host = InetAddress.getByName(host).toString();
41 }
42 catch (java.net.UnknownHostException ex) {
43 }
44 System.out.println("Host: " + host +
45 " Port :" + ll.getPort());
46 }
47 catch (RemoteException e) {
48 e.printStackTrace();
49 }
50 }
51 }
52 }
53 // PageBreak
54 public static void main(String args[]) throws Throwable {
55 if (args.length == 0) {
56 System.out.println("Usage:");
57 System.out.println(" java Joiner <rmicodebase>" +
58 " <ServiceProxyClass> [<lookup locators>...]");
59 System.exit(1);
60 }
61
62 Properties systemProp = System.getProperties();
63 systemProp.put("java.rmi.server.codebase", args[0]);
64
65 Class serveClass = Class.forName(args[1]);
66 CompoundService service =
(CompoundService)(serveClass.newInstance());
67
68 Entry [] attribs = (Entry [])(service.getAttributes());
69

Lookup and Discovery 6-43


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
70 Listen myListener = new Listen();
71
72 final JoinManager jm = new JoinManager(
73 service, attribs, myListener, new LeaseRenewalManager());
74
75 if (args.length > 2) {
76 LookupLocator [] locs = new LookupLocator[args.length - 2];
77
78 for (int i = 2; i < args.length; i++) {
79 locs[i - 2] = new LookupLocator(args[i]);
80 }
81 jm.addLocators(locs);
82 }
83
84 myListener.setJoinManager(jm);
85
86 System.out.println("type quit to remove service from lookups");
87 BufferedReader in = new BufferedReader(
88 new InputStreamReader(System.in));
89 for (;;) {
90 String line = in.readLine();
91 if (line.equalsIgnoreCase("quit")) {

6-44 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
92 jm.terminate();
93 Thread.sleep(1000);
94 System.exit(0);
95 }
96 }
97 }
98 }
99
Code 6-10 Joiner.java

The JoinManager class provides a convenient way for a service to


register with Lookup services. This class supports lease maintenance,
both Multicast and Unicast Discovery protocols, and the Multicast
Announcement Protocol. Because every service must register, this
example provides a generalized installer for services that implement
the CompoundService interface. It is easy to modify this example so it
does not depend upon that interface (which is part of this course, not
part of the Jini technology distribution). However, it is convenient for a
generalized installer to obtain the attributes for the service it is
installing from the service itself. This is one of the functions provided
by the CompoundService interface.

In operation, this example constructs an instance of the service, and an


instance of the JoinManager class. It configures the JoinManager to
install the service object with any general Lookup service it can find,
and additionally, with any explicitly named Lookup services that it
finds listed on the command line. Once set up, the example prints out
messages whenever the service is registered with a new Lookup
service, or a Lookup service dies.

In addition to configuring the JoinManager instance, this example


also monitors the command line input, waiting for the user to type
quit. When that happens, the join manager is terminated, so the
service is deregistered. If, instead of quitting, you simply kill the joiner
program, the service remains registered until the lease expires.

Lookup and Discovery 6-45


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
This example, while monitoring the progress of registration, prints
information to the standard output channel each time a new Lookup
service comes online or goes down. This functionality is not needed in
a production system, but is provided here to allow you to see what is
happening.

6-46 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6

Non-Core Classes

The classes JoinManager and LookupLocatorDiscovery are not core


classes in Jini software. They support classes provided by the Sun
Microsystems™ release of the technology. This has some implications
that you must consider before using them.

The JoinManager class is generally used by a service provider to


register service(s) with appropriate registrars. In such an environment,
you can control the Jini technology implementation that is used for
deployment, and you might decide that using the JoinManager class
is quite reasonable.

On the other hand, the LookupLocatorDiscovery class is more likely


to be used at the client end of a system, and you might have less
control over the host’s implementation of Jini technology. In a hand-
held browser (such as a mobile phone) you should not have trouble
because it is your browser running on your implementation of the
underlying technology. However, the proxy part of a service has no
control over the host system that it runs in, and, consequently, should
be restricted to operating with the core classes.

Lookup and Discovery 6-47


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
The non-core classes are provided because they fill a requirement. On
this basis, later releases of the Jini technology will include classes with
the functionality of these non-core classes, but in a core package. This
approach has been adopted to allow improvement of the design of
some of these classes before they are committed to the core package
set.

6-48 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Exercises: Using Lookup Services

Exercise objective – Use Lookup services to locate services statically


and dynamically, locate Lookup services dynamically, and register
services.

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.

Lookup and Discovery 6-49


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

6-50 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ State the software and network requirements for running Jini


technology Lookup services.

❑ State what aspect of spontaneous networking is not addressed by


Jini technology.

❑ State the purpose and benefits of Multicast Discovery, Multicast


Announcement, and Unicast Discovery protocols.

❑ Write code using the Jini technology distribution classes to use the
Discovery and Announcement protocols.

❑ Write code using the ServiceRegistrar and supporting classes


to use the facilities of a Jini technology Lookup service both as a
client and as a service provider

❑ Distinguish between core and non-core Jini technology


distribution classes

❑ Write code to implement a simple Jini service and apply attributes


to that service

❑ Use the transient keyword in conjunction with accessor methods


to handle non-serializable elements of a service class.

Lookup and Discovery 6-51


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
6
Think Beyond

● How would you decide on the defining interface, or interfaces, for


a service?

● How general should you make these interfaces?

● How might you use the attributes of a service? To assist clients in


selecting a service? To notify status of a service?

6-52 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Putting it Together 7

Objectives
Upon completion of this module, you should be able to:

● Design and implement complex systems using Jini technology

7-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Relevance

Discussion – In the previous module, you looked at a number of


elements of Jini technology in isolation. To build a fully functional Jini
technology-based system, you need to be able to handle the
complexity of all these elements simultaneously.

7-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Example of Putting it Together

The following is an example of using many elements of Jini


technology.
1 import java.io.*;
2 import java.util.*;
3 import java.rmi.server.UnicastRemoteObject;
4 import java.rmi.*;
5 import com.sun.jini.lease.LeaseRenewalManager;
6 import net.jini.discovery.LookupDiscovery;
7 import com.sun.jini.discovery.LookupLocatorDiscovery;
8 import net.jini.core.lookup.ServiceTemplate;
9 import net.jini.core.discovery.LookupLocator;
10 import net.jini.core.lease.Lease;
11 import net.jini.discovery.DiscoveryListener;
12 import net.jini.discovery.DiscoveryEvent;
13 import net.jini.core.event.RemoteEventListener;
14 import net.jini.core.event.RemoteEvent;
15 import net.jini.core.lookup.ServiceRegistrar;
16 import net.jini.core.lookup.ServiceMatches;
17 import net.jini.core.lookup.ServiceID;
18 import net.jini.core.event.EventRegistration;
19 import net.jini.core.lease.UnknownLeaseException;
20 import net.jini.core.lookup.ServiceItem;
21
22 public class MapAll extends UnicastRemoteObject
23 implements DiscoveryListener, RemoteEventListener {
24
25 private HashMap registrars = new HashMap();
26 private HashMap services = new HashMap();
27 private boolean servsUpToDate = false;
28 private LeaseRenewalManager leaseRenewalManager =
29 new LeaseRenewalManager();
30
31 private LookupDiscovery ld;
32 private LookupLocatorDiscovery lld;
33 private String [] groups;
34 private ServiceTemplate template;
35 private LookupLocator [] specificLocators;
36
37 private Vector listeners = new Vector();
38
39 // this is a "data structure" class that keeps the lease for a
40 // particular registrar alongside a HashMap for the services

Putting it Together 7-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
41 // in that registrar. Items of this class are the contents
42 // of the "registrars" HashMap
43 private static class RegInfo {
44 public HashMap servMap;
45 public Lease listenerLease;
46 };
47 // PageBreak
48 public MapAll(String [] groups,
49 LookupLocator [] specificLocators,
50 ServiceTemplate template) throws RemoteException {
51
52 String [] emptyStringArray = {};
53 this.groups = (groups != null) ? groups : emptyStringArray;
54 this.specificLocators = specificLocators;
55 this.template = (template != null) ? template :
56 new ServiceTemplate(null, null, null);
57
58 // start a multicast discovery process looking for
59 // registrars in all interesting groups, and listen
60 // for the callbacks that arise from this
61 try {
62 ld = new LookupDiscovery(groups);
63 ld.addDiscoveryListener(this);
64 }
65 catch (IOException ex) {
66 ex.printStackTrace();
67 }
68
69 // start a unicast discovery process, looking for and
70 // keeping track of specific registrars (don’t consider
71 // groups for these). Ask for callbacks on these too
72 lld = new LookupLocatorDiscovery(specificLocators);
73 lld.addDiscoveryListener(this);
74 }
75
76 // this method builds a list of up to 500 (arbitrary limit) services
77 // for a particular registrar. These are keyed against the service
78 // ID.
79 private void populateRegistrarMap(ServiceRegistrar reg, Map map)
80 throws RemoteException {
81 map.clear();
82 ServiceMatches sm = reg.lookup(template, 500);
83 for (int i = 0; i < sm.items.length; i++) {
84 map.put(sm.items[i].serviceID, sm.items[i]);
85 }
86 }

7-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
87 // PageBreak
88 // This method is called when a new registrar has been reported
89 public void discovered(DiscoveryEvent e) {
90 // get the list of new registrars
91 ServiceRegistrar [] regs = e.getRegistrars();
92 // for each one
93 for (int i = 0; i < regs.length; i++) {
94 // get the service id
95 ServiceID id = regs[i].getServiceID();
96 // and see if we already know about it
97 RegInfo regInfo = (RegInfo)(registrars.get(id));
98 if (regInfo == null) {
99 regInfo = new RegInfo();
100 // if it’s new, create a fresh map
101 regInfo.servMap = new HashMap();
102 // and put it into the big scheme of things
103 registrars.put(id, regInfo);
104 }
105 else {
106 // if we know about the registrar already do not create
107 // new storage for it, but lose the old listener lease
108 try {
109 // cancel the old lease
110 leaseRenewalManager.cancel(regInfo.listenerLease);
111 }
112 catch (UnknownLeaseException ex) {
113 // don’t care, we didn’t want it anyway
114 // but for info, print it
115 ex.printStackTrace();
116 }
117 catch (RemoteException ex) {
118 // don’t care, we didn’t want it anyway
119 // but for info, print it
120 ex.printStackTrace();
121 }
122 }
123// PageBreak
124 try {
125 populateRegistrarMap(regs[i], regInfo.servMap);
126 // ask to be told when anything happens that might interest us
127 EventRegistration evReg = regs[i].notify(template,
128 ServiceRegistrar.TRANSITION_MATCH_MATCH +
129 ServiceRegistrar.TRANSITION_MATCH_NOMATCH +
130 ServiceRegistrar.TRANSITION_NOMATCH_MATCH,
131 this,
132 new MarshalledObject(regs[i]),

Putting it Together 7-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
133 Lease.ANY);
134 regInfo.listenerLease = evReg.getLease();
135 // ask for this to be renewed forever
136 leaseRenewalManager.renewUntil(regInfo.listenerLease,
Lease.ANY, null);
137 }
138 catch (IOException ex) {
139 // shouldn’t happen, ServiceRegistrar must be serializable
140 ex.printStackTrace();
141 registrars.remove(id);
142 }
143 }
144 // notify that we’ve a new service set
145 servsUpToDate = false;
146 notifyServicesChanged();
147 }
148
149 public void discarded(DiscoveryEvent e) {
150 }
151// PageBreak
152 // this is the callback method for registrars informing us
153 // that the set of services registered with them has changed
154 // in some way
155 public void notify(RemoteEvent e) {
156 try {
157 // when we registered for this event, we put the registrar
158 // into the handback object - fetch it out again
159 ServiceRegistrar service =
160 (ServiceRegistrar)(e.getRegistrationObject().get());
161 // determine which service ID this registrar uses, that
162 // is used as the key when we put this into the hashtable
163 RegInfo regInfo =
(RegInfo)(registrars.get(service.getServiceID()));
164 // this shouldn’t happen - we only expect callbacks from
registrars
165 // we’ve already seen. They should, therefore, be in the map
166 if (regInfo == null) {
167 // recover the anomaly by creating a new entry for the map
168 regInfo = new RegInfo();
169 regInfo.servMap = new HashMap();
170 registrars.put(service, regInfo);
171 }
172 HashMap map = regInfo.servMap;
173 // build the registrar specific sub-map
174 try {
175 populateRegistrarMap(service, map);

7-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
176 }
177 catch (RemoteException ex) {
178 // if this registrar died, take it out
179 registrars.remove(service);
180 }
181 servsUpToDate = false;
182 notifyServicesChanged();
183 }
184 catch (ClassNotFoundException ex) {
185 ex.printStackTrace();
186 }
187 catch (IOException ex) {
188 ex.printStackTrace();
189 }
190 }
191// PageBreak
192 // this method builds a list of all services, keeping the "last
193 // seen" reference for each one in a separate map. This hides
194 // duplicates that arise because a service is registered with
195 // multiple registrars. When the new table is built, listeners
196 // are notified with a "ServiceEvent"
197 private void notifyServicesChanged() {
198 try {
199 services.clear();
200 Iterator i1 = registrars.values().iterator();
201 while (i1.hasNext()) {
202 HashMap forReg = ((RegInfo)(i1.next())).servMap;
203 Iterator i2 = forReg.values().iterator();
204 while (i2.hasNext()) {
205 ServiceItem si = (ServiceItem)(i2.next());
206 ServiceID sid = si.serviceID;
207 services.put(sid, si);
208 }
209 }
210 ServiceEvent ev = new ServiceEvent(this, services.values());
211 Iterator i3 = listeners.iterator();
212 while (i3.hasNext()) {
213 ServiceListener sl = (ServiceListener)(i3.next());
214 sl.notifyServices(ev);
215 }
216 }
217 catch (Throwable t) {
218 t.printStackTrace();
219 }
220 }
221

Putting it Together 7-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
222 public void addServiceListener(ServiceListener l) {
223 listeners.add(l);
224 }
225
226 public void removeServiceListener(ServiceListener l) {
227 listeners.remove(l);
228 }
229
230 public Iterator getServices() {
231 return services.values().iterator();
232 }
233// PageBreak
234 public static void main(String args[]) throws Throwable {
235 System.setSecurityManager(new SecurityManager());
236 String [] groups = {};
237 LookupLocator [] specificLocators = null;
238 if (args.length > 0) {
239 specificLocators = new LookupLocator[args.length];
240 for (int i = 0; i < specificLocators.length; i++) {
241 specificLocators[i] = new LookupLocator(args[i]);
242 }
243 }
244 ServiceTemplate template = null;
245 final MapAll ma = new MapAll(groups, specificLocators, template);
246
247 ma.addServiceListener(
248 new ServiceListener() {
249 public void notifyServices(ServiceEvent ev) {
250 System.out.println("New service list:");
251 Iterator i = ev.getServices().iterator();
252 while (i.hasNext()) {
253 ServiceItem item = (ServiceItem)(i.next());
254 System.out.println("Service id " + item.serviceID +
255 " is a " + item.service.getClass().getName());
256 }
257 }
258 }
259 );
260
261 for (;;) {
262 Thread.sleep(15000);
263 System.out.print(".");
264 System.out.flush();
265 }
266 }
267}
Code 7-1 MapAll.java

7-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
The MapAll Class
This example is a self-contained class that monitors all multicast-
accessible Lookup services, while simultaneously monitoring a
number of explicitly-named services that might not be available using
Multicast protocols.

When it starts, it begins both Multicast and Unicast Discovery


protocols and lists all the services found in any Lookup services
located in this way. Once started, it also continues to monitor for new
Lookup services.

The MapAll class also registers with each Lookup service that is
located, asking for notification about any services that are added,
removed, or modified.

Whenever a new Lookup service is found, or any service comes online,


goes off line, or changes its attributes, the MapAll object prints a
message indicating the current set of services that are available.

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.

Investigating the Code for the MapAll Classes


This section describes the essential elements of the MapAll class.

The variable registrars refers to a HashMap (line 25) containing


RegInfo (line 43) objects.

The HashMap called servMap (line 44) contains the service proxies for
the registrar, indexed by serviceID.

Putting it Together 7-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
The lease called listenerLease (line 45) holds the lease on event
registration that was granted by the Lookup service when we asked to
be notified of all new services, changes in services, or de-registered
services (lines 126-134)

The discovered method (lines 89-147) is used to populate the


HashMap that keeps track of all known registrars. The methods
discovered and discarded together implement the
DiscoveryListener (line 23) interface. The calls to discovered and
discarded come from the LookupDiscovery (lines 62-63) and
LookupLocatorDiscovery (lines 72-73) objects that are created in
MapAll’s constructor (lines 58-76). In this implementation of the
MapAll class, the discarded method is never called.

The MapAll object is registered as a listener on both the


LookupDiscovery and LookupLocatorDiscovery objects (lines 63
and 73). While the LookupDiscovery and LookupLocatorDiscovery
objects are responsible for recognizing the addition and removal of
Lookup services, the MapAll object itself is a RemoteEventListener
(line 23) and its notify method (lines 168-206) is called by Lookup
services (using RMI) when new services register, details of a registered
service change, or a service is de-registered.

The notify method rebuilds the contents of one RegInfo object -


specifically, the RegInfo object that describes the Lookup service that
issued the notification (line 179). To do this, the notify method first
obtains a reference to the service registrar that issued the notify call
(line 176). This reference supplies the ServiceID of the registrar (line
179) and this ID is used to search the registrars HashMap for the related
RegInfo object (line 179).

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 method populateRegistrarMap (lines 76-86) empties the


argument map (line 81) and then asks the Lookup service for up to 500
of its entries (line 82). These entries are then placed in the map (lines
82-85) using their ServiceID values as keys.

7-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
The notifyServicesChanged method (lines 208-236) collates all the
services found in all Lookup services so that duplicates are removed
and a single list is prepared. To do this, the method iterates through
the registrars HashMap (lines 216-217) and for each entry, it iterates the
list of services in the servMap (lines 218-220) field of the RegInfo
object, extracting each service object (line 221) and ServiceID object
(line 222) and puts them into the services HashMap (line 223). Because
a HashMap cannot have duplicate keys, multiple references to the same
service (the same ServiceID) are merged into a single entry in the
services HashMap. After the services HashMap has been populated, any
registered listeners are notified. This notification is achieved by
iterating the vector listeners (lines 227-228) and calling each
listener’s notifyServices method (line 230) with a ServicesEvent
object that describes the new services list (line 226).

Putting it Together 7-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
The Browse Class

The following code example generates a browser.


1 import java.awt.*;
2 import java.awt.event.*;
3 import java.applet.*;
4 import javax.swing.*;
5 import java.net.*;
6 import java.rmi.*;
7 import java.util.*;
8 import net.jini.core.lookup.ServiceItem;
9 import net.jini.core.lookup.ServiceTemplate;
10 import net.jini.core.discovery.LookupLocator;
11 import net.jini.lookup.entry.ServiceType;
12
13 public class Browse extends JPanel
14 implements ServiceListener {
15
16 private JSplitPane splitPane;
17 private JList serviceList;
18 private JTabbedPane displayPanel;
19 private ServiceListRenderer renderer;
20 private DefaultListModel listModel;
21
22 private JMenuBar menuBar;
23 private JMenu controlMenu;
24 private JMenuItem startServiceItem;
25
26 private MapAll map;
27 // PageBreak
28 // This method is called to start the service associated with
29 // the currently selected list item. This is only possible if
30 // that current entry implements the CompoundService interface
31 private void startCurrent() {
32 // find the current item in the list
33 ServiceItem item = (ServiceItem)(serviceList.getSelectedValue());
34
35 // check that it’s some kind of component
36 if ((item != null) && (item.service instanceof CompoundService) )
{
37 // cast it for future use
38 Component c = ((CompoundService)(item.service)).getUI();
39
40 // get the service type

7-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
41 ServiceType type = renderer.getServiceType(item);
42 // and determine an appropriate presentation name
43 String title = null;
44 if (type != null) {
45 title = type.getDisplayName();
46 }
47 else {
48 title = c.getClass().getName();
49 }
50
51 // add the component to the tabbed pane, with its title
52 JPanel jp = new JPanel();
53 jp.setLayout(new BorderLayout());
54 jp.add(c, BorderLayout.CENTER);
55 displayPanel.add(title, c);
56 displayPanel.validate();
57
58 // if it’s an Applet, call it’s init and start methods
59 if (c instanceof Applet) {
60 Applet a = (Applet)c;
61 a.init();
62 a.start();
63 }
64 }
65 }
66 // PageBreak
67 // Build the GUI and set up the browser, connected to a MapAll
object
68 public Browse(String [] locators)
69 throws MalformedURLException, RemoteException {
70 setLayout(new BorderLayout());
71 listModel = new DefaultListModel();
72 serviceList = new JList(listModel);
73 renderer = new ServiceListRenderer();
74 serviceList.setCellRenderer(renderer);
75 JScrollPane jsp = new JScrollPane(serviceList);
76
77 displayPanel = new JTabbedPane();
78
79 splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
80 jsp, displayPanel);
81 add(splitPane, BorderLayout.CENTER);
82
83 LookupLocator [] specificLocators =
84 new LookupLocator[locators.length];
85 for (int i = 0; i < locators.length; i++) {

Putting it Together 7-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
86 specificLocators[i] = new LookupLocator(locators[i]);
87 }
88 String [] groups = {};
89 ServiceTemplate template = null;
90 map = new MapAll(groups, specificLocators, template);
91 map.addServiceListener(this);
92
93 menuBar = new JMenuBar();
94 add(menuBar, BorderLayout.NORTH);
95 controlMenu = new JMenu("Control");
96 menuBar.add(controlMenu);
97 startServiceItem = new JMenuItem("Launch Service");
98 controlMenu.add(startServiceItem);
99 startServiceItem.addActionListener(
100 new ActionListener() {
101 public void actionPerformed(ActionEvent ev) {
102 startCurrent();
103 }
104 }
105 );
106 }
107// PageBreak
108 // This is the listener method. It is called when the MapAll
109 // object has a change in the list of services.
110 // This reacts by updating the list in the display.
111 public void notifyServices(ServiceEvent ev) {
112 Iterator i = ev.getServices().iterator();
113
114 DefaultListModel listModel = new DefaultListModel();
115 while (i.hasNext()) {
116 ServiceItem item = (ServiceItem)(i.next());
117 listModel.addElement(item);
118 }
119 this.listModel = listModel;
120 serviceList.setModel(this.listModel);
121 }
122
123 public Dimension getPreferredSize() {
124 Dimension d = super.getPreferredSize();
125 Dimension right = displayPanel.getPreferredSize();
126 if (right.width < 300) {
127 d.width = d.width - right.width + 300;
128 }
129 if (d.height < 300) {
130 d.height = 300;
131 }

7-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
132 return d;
133 }
134
135 public static void main(String args[]) throws Throwable {
136 System.setSecurityManager(new SecurityManager());
137 Browse b = new Browse(args);
138 JFrame jf = new JFrame("Jini Services");
139 jf.getContentPane().add(b, BorderLayout.CENTER);
140 jf.pack();
141 jf.setVisible(true);
142 }
143}
Code 7-2 Browse.java

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.

When you select a service, method startCurrent (lines 28-65) starts


that service. If the selected service is an instance of CompoundService
(line 36), then that service’s getUI method is called (line 38). A tabbed
pane is created on the right side of the display, containing the interface
for the selected service.

Putting it Together 7-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7

Running the Examples

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

7-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
You must specify the security options on the command line. You
should specify the rmi codebase as the first argument, and the service
class to install should be the second argument.

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.

Putting it Together 7-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Exercise: Investigating Service Proxy-to-Service
Communication

Exercise objective – Create a two part service so that some work is


done on the service host, and some at the service proxy on the client.

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.

7-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

Putting it Together 7-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Design and implement complex systems using Jini technology

7-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
7
Think Beyond

What, if any, constraints does Jini technology impose on service-to-


service proxy communications?

What options do you have for handling a pre-existing networked


device that does not run a JVM, and cannot have new code loaded?

Putting it Together 7-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Jini Transactions 8

Objectives
Upon completion of this module, you should be able to:

● Describe the similarities and differences between Jini transactions


and database transactions.

● Outline the states that a Jini transaction can be in, and state the
significance of each state

● Write code to create a new transaction using a transaction manager


service

● Write a transaction participant, including joining the transaction,


committing, or aborting the transaction, and responding to
instructions from the transaction manager.

● State the requirements of transaction participant behavior in the


face of concurrent access.

● Write code to obtain and use instances of the restricted interface


Transaction

8-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Relevance

Discussion – If different parts of a job are being performed in different


locations, it is important that each part be aware of any difficulties that
happen to arise in the other parts. Under such conditions, the system
design must provide for a clean result, generally either complete
success or complete failure, but avoiding situations where different
parts of the system are in inconsistent states. This is the job of
transactions.

8-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

What Are Jini Transactions?

A transaction is a group of operations that must either fully succeed or


cause no permanent effect at all. For example, if you are trying to
perform a multi-step operation on an object in a distributed system,
you must ensure that if any of the partial operations fail, then the
effect of all of them is nullified.

In this sense, Jini transactions are similar to database management


system (DBMS) transactions. However, there are important differences.
In a DBMS, the transaction is created and managed by the DBMS itself
and there is only one other participant—the client. In a Jini technology
system, a transaction can be created and controlled on one system,
while any number of other systems are participating in the same
transaction, some providing data, some performing operations.
Another significant difference between these two types of transactions
is that Jini technology does not specify the exact semantics of a
transaction; you can create transaction managers that implement a
specific set of semantics that are appropriate to your needs.

Jini Transactions 8-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Jini transactions use a two-phase commit concept. The first phase
involves polling all the interested parties to determine if they believe it
is appropriate to roll the transaction forward. If all the parties agree
that this is appropriate, then the transaction commits. However, if any
party cannot complete the transaction, or if any participant has failed,
or is otherwise unreachable, then the commit cannot proceed.

8-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Transaction States

In any transaction, there is the transaction manager and the transaction


actors. For any single transaction, there can be only one manager, but
there can be any number of actors. Many of the actors implement the
interface net.jini.core.transaction.server.participant. These
actors are called participants.

The transactions behave as a state machine, for both participants and


the transaction in the transaction manager. There are a number of
states defined by the APIs, and a defined set of paths through the
states.

A newly created transaction in a manager starts in the ACTIVE state. It


remains there as new participants join the transaction, and as they
perform operations. Eventually, an actor (which might actually be a
participant) calls either the commit or abort method. If commit is
called, the transaction manager moves to the VOTING state, and
perhaps ultimately to the COMMITTED state, if all the participants
agree; otherwise the transaction is aborted.

Jini Transactions 8-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
From the participants’ point of view, the process has more states.
When a participant first joins a transaction, the participant is in the
ACTIVE state. Eventually, the transaction manager either aborts the
transaction (usually in response to a request from some other
participant) or allows the transaction to complete successfully.
Successful completion usually moves through the PREPARED and
COMMITTED states in sequence. If a participant has not been
changed, it can be in the NOTCHANGED state, which allows it to
drop out of the transaction and simplify the commit phase.

The following sections look at successful and unsuccessful transactions


in detail.

8-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Starting a Transaction

To create a new transaction, you must locate a transaction manager.


You locate a transaction manager using either the rmiregistry or a
Jini technology Lookup service. The details of the Jini technology
Lookup service mechanisms are the subject of the next module, and
are not discussed here.

If you have a remote reference to a TransactionManager, you


simply call the create method, indicating the lease duration you
would like for the transaction. This returns an instance of the
TransactionManger.Created inner class. This object contains two
fields, the lease that was issued for the transaction, and the ID of the
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.

Jini Transactions 8-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
All participants should keep track of their state at the moment they
join the transaction, so that if the transaction aborts they can restore
this state, rolling back the transaction. Two distinct states are part of
this discussion: the state of the transaction, and the state of the
transaction participants. At the start of a transaction, the participants
are all in the ACTIVE state, but the state of the transaction participant
is determined by the data in the participant. In some participants,
there is no significant state that might need to be rolled back. For
example, the actor that initiates the transaction might have no relevant
state, instead, it is responsible for invoking all the operations that
make the transaction. In these circumstances, it might be appropriate
for the actor not to be a participant.

8-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Successfully Completing a Transaction

When a participant calls commit on the TransactionManager, the


TransactionManager moves to the VOTING state and calls the
prepare method of each participant. In a successful transaction, each
participant returns to either the NOTCHANGED or PREPARED state.
A return of NOTCHANGED is appropriate if the state of the
participant has not been changed by this transaction or if there was no
state associated with this transaction. This return allows the
participant to drop out of the transaction and the manager to remove
the participant from the transaction. Alternatively, for a successful
transaction, the participant might return the PREPARED state. This
indicates that all operations of this transaction have been successful,
and the participant can proceed to a commit. From this point, the
participant should wait for the commit from the manager.

After a successful return from each prepare call, the manager


proceeds to commit the transaction. To commit the transaction, the
manager calls the commit method of each remaining participant.

Jini Transactions 8-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Failure of a Transaction

A transaction can fail for several different reasons. An individual


participant can call the abort method of the TransactionManager
explicitly. This would be appropriate if the participant cannot properly
complete some operation that was invoked in the context of this
transaction.

If a participant returns ABORTED from the prepare call, the


TransactionManager aborts the entire transaction. Similarly, if the
lease times out or if a RemoteException arises during the
TransactionManager’s communication with participants, the
TransactionManager aborts the transaction.

When a TransactionManager aborts a transaction, it calls the


abort method of each of the participants. Each participant is then
responsible for rolling back its state so that it appears that none of the
operations in the transaction ever happened.

8-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
If a participant calls the commit method and the failure occurs while
the TransactionManager is attempting to complete the commit
operation, the commit method throws a CannotCommitException
to its caller.

A difficult type of failure can occur if a transaction is in the


commitment phase, that is, all the participants are prepared, and some
are committed, and one or more of the uncommitted participants, or
the transaction manager itself, fails. There is no way to recover from a
permanent failure of this kind, and the best that can be done is to
ensure that all participants and managers are coded so they can
recover and restart after a failure. The RMI activation system is a
convenient way to achieve this.

Jini Transactions 8-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Rejoining a Transaction

If a participant crashes, it can try to rejoin the transaction when it


comes back up. To do this, it must indicate to the transaction manager
that it knows it crashed. This is done by using a crash count value, that
should be incriminated (starting from zero) at each rejoin attempt.

The purpose of the crash count variable is a sanity check. If the


participant has restarted, but cannot correctly increment its own
integer crash count value, then it is unsafe to allow it to rejoin the
transaction and the transaction is aborted.

8-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Transactions and Concurrent Access

It is quite common to have transaction participants that accept


concurrent calls, some of which are part of a transaction and some of
which are part of another transaction, or not part of a transaction at all.
In these situations, the behavior of a method that is not part of the
transaction might depend on the outcome of the transaction as a
whole.

Consider this scenario involving a storage service. Initially, the store


contained object X that had been taken out of the store under a
transaction that has not yet concluded. If another client tries to do a
read of object X, what happens? The store might return object X, on the
basis that the object is still there until and unless the transaction
completes successfully. Alternatively, the store could block the read
call until the transaction concludes, and then return appropriately. The
store should not "assume" that the transaction will complete
successfully, returning without the object.

So, which of these two (or three depending on your perspective)


approaches should you take? You might have to make this choice, and
the basis of your choice must be the particular semantics of the

Jini Transactions 8-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
participant you are creating. Blocking under a time-out in the hope
that the transaction will complete is a common and reasonable
approach.

8-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Transactions Example

The following demonstrates the implementation of the participant


methods. When it is run, it shows the effect and flow of the various
forms of fragmentation completion.
1 import java.util.Date;
2 import java.rmi.server.UnicastRemoteObject;
3 import java.rmi.RemoteException;
4 import net.jini.core.discovery.LookupLocator;
5 import net.jini.core.lookup.ServiceRegistrar;
6 import net.jini.core.lookup.ServiceTemplate;
7 import net.jini.core.transaction.server.TransactionManager;
8 import net.jini.core.transaction.server.TransactionParticipant;
9 import net.jini.core.transaction.server.CrashCountException;
10 import net.jini.core.transaction.Transaction;
11 import net.jini.core.transaction.UnknownTransactionException;
12 import net.jini.core.transaction.CannotJoinException;
13 import net.jini.core.transaction.CannotCommitException;
14 import net.jini.core.transaction.CannotAbortException;
15 import net.jini.core.lease.Lease;
16 import net.jini.core.lease.LeaseDeniedException;
17
18 public class Trans1 extends UnicastRemoteObject
19 implements TransactionParticipant {
20
21 public static final long ONE_MIN = 60 * 1000;
22 private TransactionManager meagre;
23 private static in identNumber = 0;
24 private String name;
25
26 public Trans1() throws RemoteException {
27 name = "Participant " + identNumber++;
28 }
29
30 public Trans1(TransactionManager mgr) throws RemoteException {
31 this();
32 this.mgr = mgr;
33 }
34
35 public void connectWith(TransactionManager mgr,
36 TransactionManager.Created tc) throws RemoteException,
37 CrashCountException, CannotJoinException,
38 UnknownTransactionException {
39

Jini Transactions 8-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
40 this.mgr = mgr;
41 this.mgr.join(tc.id, this, 0);
42
43 System.out.println(name + " joined transaction");
44 }
45 // PageBreak
46 public void go() throws RemoteException, LeaseDeniedException {
47 TransactionManager.Created tc = mgr.create(ONE_MIN);
48 Trans1 theOther = new Trans1();
49
50 System.out.println("got a transaction.created, lease until: " +
51 new Date(tc.lease.getExpiration()));
52
53 try {
54 mgr.join(tc.id, this, 0);
55 System.out.println("Joined the transaction");
56 theOther.connectWith(mgr, tc);
57
58 if (Math.random() > 0.5) {
59 System.out.println("Calling commit");
60 mgr.commit(tc.id);
61 }
62 else {
63 System.out.println("Calling abort");
64 mgr.abort(tc.id);
65 }
66 }
67 catch (CrashCountException cce) {
68 cce.printStackTrace();
69 }
70 catch (UnknownTransactionException ute) {
71 ute.printStackTrace();
72 }
73 catch (CannotCommitException ccme) {
74 ccme.printStackTrace();
75 }
76 catch (CannotAbortException cae) {
77 cae.printStackTrace();
78 }
79 catch (CannotJoinException cje) {
80 cje.printStackTrace();
81 }
82 }
83
84 public void abort(TransactionManager mgr, long id) {
85 System.out.println("In " + name + " abort called");

8-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
86 }
87
88 public void commit(TransactionManager mgr, long id) {
89 System.out.println("In " + name + " commit called");
90 }
91 // PageBreak
92 public int prepare(TransactionManager mgr, long id) {
93 System.out.println("In " + name + " prepare called");
94 if (Math.random() > 0.7) {
95 System.out.println("In " + name + "returning PREPARED");
96 return PREPARED;
97 }
98 else if (Math.random() > 0.6) {
99 System.out.println("In " + name + "returning NOTCHANGED");
100 return NOTCHANGED;
101 }
102 System.out.println("In " + name + "returning ABORTED");
103 return ABORTED;
104 }
105
106 public int prepareAndCommit(TransactionManager mgr, long id) {
107 System.out.println("In " + name + "prepareAndCommit called");
108 int result = prepare(mgr, id);
109 if (result == PREPARED) {
110 commit(mgr, id);
111 result = COMMITTED;
112 }
113 return result;
114 }
115
116 public static void main(String args[]) throws Throwable {
117 LookupLocator ll = new LookupLocator(args[0]);
118 ServiceRegistrar reg = ll.getRegistrar();
119 Class [] classes = { TransactionManager.class };
120 ServiceTemplate templ = new ServiceTemplate(null, classes, null);
121 TransactionManager mgr = (TransactionManager)(reg.lookup(templ));
122 Trans1 that = new Trans1(mgr);
123 that.go();
124 }
125}
Code 8-1 Trans1.java

Jini Transactions 8-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
The example starts with the main method which uses the Jini
technology Lookup service to locate the Jini Transaction service. The
code first locates the transaction manager, then passes a reference to it
into the constructor of the Trans1 class. When the newly constructed
Trans1 object is returned, the go method is invoked upon it.

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.

The go method next prints a message indicating that a transaction has


been started and the lease expiry that was received for it. This example
ignores the lease, assuming that the transaction completes long before
the lease times out. If this is not a safe assumption in code that you
write, then you should handle the lease appropriately.

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.

Depending on the choice made by the first participant, the transaction


manager tries to complete the transaction. If the original decision was
to commit the transaction, then it proceeds to call the prepare
method on each participant. If each participant responds to the
prepare call with either PREPARED or NOTCHANGED, then the
transaction manager calls the commit method of each participant. In
some cases, the last call to prepare is replaced with a
prepareAndCommit call.

8-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Additional Transaction Classes

The TransactionParticipant interface provides all the methods


needed for full participation in a transaction. In addition, the
TransactionManager interface, along with a
TransactionManager.Created instance to identify a particular
transaction, provide all that is needed to attach to a transaction, and to
control that transaction.

Sometimes, however, it would be better if transactions could be passed


around with less information being given away. To do this, the
Transaction interface, which supports only the methods commit
and abort is defined. You can use this interface when you want
additional information.

You must use the Transaction interface with the JavaSpaces


technology service. In fact, the sample implementation of JavaSpaces
technology requires that the actual Transaction object it receives
must be an instance of the class
net.jini.core.transaction.ServerTransaction.

Jini Transactions 8-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
To implement the Transaction interface, create a small class that
contains references to both the TransactionManager and
TransactionManager.Created objects, and provide the required
methods by proxying the calls into the manager, using the ID from the
created object to identify the transaction.

8-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8

Additional Transaction Classes

In support of the Transaction interface, there is a core transaction


class called TransactionFactory that you can call to create
Transaction objects from a given TransactionManager. Usually the
actual object this factory returns implements more functionality than
simply the Transaction interface. In the default implementation, the
object is actually an instance of the class
net.jini.core.transaction.ServerTransaction. As
discussed in the previous slide, this behavior might be important to a
client, such as an implementation of the JavaSpaces technology
service.

Jini Transactions 8-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Exercise: Investigating Transaction Sequencing

Exercise objective – In this exercise you will create a simple


transaction participant that exemplifies the commit and rollback
behavior.

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.

8-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

Jini Transactions 8-23


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Describe the similarities and differences between Jini transactions


and database transactions.

❑ Outline the states that a Jini transaction can be in, and state the
significance of each state.

❑ Write code to create a new transaction using a transaction manager


service

❑ Write a transaction participant, including joining the transaction,


committing, or aborting the transaction, and responding to
instructions from the transaction manager.

❑ State the requirements of transaction participant behavior in the


face of concurrent access.

❑ Write code to obtain and use instances of the restricted interface


Transaction.

8-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
8
Think Beyond

How might you handle a participant crash between prepare and


commit?

Jini Transactions 8-25


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
JavaSpaces Technology 9

Objectives
Upon completion of this module, you should be able to:

● State the strengths of the JavaSpaces technology, and contrast it


with databases

● List the requirements for an Entry in a space

● Write code to use the methods of the JavaSpace interface

● Implement an anonymous inter-process communication scheme


using spaces

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)?

9-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Overview of JavaSpaces Technology

The main feature of JavaSpaces technology is the JavaSpaces


technology service. A JavaSpaces technology service is an object
storage mechanism. Like a client server database, you can access space
remotely using the network. However, a space does not require any
structure in the data that it stores, rather, it acts as a container for
objects.

When you want to get an entry out of a space, you do so by issuing a


request in the form of "give me something like this." That is, your
request carries a template object that is used to search for a matching
entry. The class of the object you provide is matched against the class
of objects in the store, and if a match is found, the values of non-null
fields in the template are compared with the values of fields in the
stored object.

JavaSpaces Technology 9-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
You can also use a space to issue a remote event if an object that
matches a template is written to the space. This is like asking the space
"tell me if you see something like this."

There are no constraints limiting how the storage of a JavaSpaces


technology service can be implemented. In particular, different
implementations of spaces might handle persistence differently. Some
applications require spaces that store their contents on persistent
storage (disk files), while other applications do not require persistence.

Similarly, you can use multiple spaces as a means of providing


replication. JavaSpaces technology services do not automatically
handle the issues that arise with replication, such as consistency, but
you can add such a feature in a given implementation. In fact, in some
applications, you can use multiple spaces to provide a degree of
resilience without special handling of the consequences of replication.

9-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Using JavaSpaces Technology Services

You can use JavaSpaces technology services in a variety of distributed


applications. Essentially, an application that requires sharing of data
between elements of a distributed system, notification from one
system to another, or even the distribution of code between systems,
might be a potential JavaSpaces technology services application.

For example, in a workflow application, someone requesting to


purchase a part can use a local application to create a request object.
When prepared, that request object can be written into the space,
which causes one or more other systems to be notified that the request
has been made. When those systems receive this notification, they can
obtain a copy of the request from the space and perform the next stage
of the processing, perhaps authorization or budget approval. When the
second stage of processing has been completed, the responsible
application can write the modified request object back into the space,
perhaps causing notification to be sent to some other program that
uses the notification as a trigger to read the request object and place
the order. You can extend this sequence of writing to the space,
notifying an interested party, and proceeding with the next stage of the
workflow processing as far as is required.

JavaSpaces Technology 9-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
In its most general form you can look on space as a form of
interprocess communication. It is a particularly flexible form of
interprocess communication because it operates across the network.

A particularly valuable feature of a JavaSpaces technology service is


that the data it stores is genuinely objects; that is, they define both
state and behavior. Because of this you can use a JavaSpace technology
service as a means of distributing code as well as information. This can
form the foundation of a flexible distributed processing or agent
system.

A careful design using JavaSpaces technology services can produce


highly decoupled systems. The workflow application suggested earlier
is effectively composed of many small applications but, by using the
space as the means of communication between them, each is largely
independent of the other. What matters is that the objects that they
pass around (in this example, request objects) implement an
appropriate interface that is understood by all of them.

9-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Comparing JavaSpaces Technology Services and Databases

Because JavaSpaces technology services provide a means of storing


information, it is tempting to compare them with databases. However,
when making that comparison, the most important points are the
differences between the two. You should avoid thinking of the space as
the Jini technology answer to a database.

One of the most fundamental differences is that while a database


stores only data, and that data is in a highly structured format, a space
stores objects. Because of the nature of the RMI system, which
provides the foundations for JavaSpaces technology, these are real
objects with both state and behavior.

Database searches are typically performed using a language like


structured query language (SQL), to look for records that satisfy
potentially complex expressions describing the contents of individual
fields. By contrast, in a JavaSpaces technology service, the
fundamental basis for searching is the class of the object stored. Once
an object with the appropriate class is found, the search can continue
by checking for particular fields that contain data that match the fields

JavaSpaces Technology 9-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
of a template. For example, comparative field matching, such as "find
fields alphabetically after Jones," is not possible with the JavaSpaces
technology services developed by Sun Microsystems.

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.

9-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Comparing JavaSpaces Technology Services and Databases

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.

The primary function of a database is to store data. Because of this,


once a data item has been written into a database, it is expected to stay
there, even if the system is turned off or explicitly removed. By
contrast, the storage space in a space is leased. This means that if the
system that wrote the entry into the space goes down, that entry is
removed when the lease expires.

JavaSpaces Technology 9-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Comparing JavaSpaces Technology Services and Databases

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.

Databases, by means of query languages, provide powerful


mechanisms for modifying the data stored in them. However, spaces
provide storage only for static copies of objects. The only way to
change an object, or part of an object, is to remove the object, modify
it, and write it back to the space.

9-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Comparing JavaSpaces Technology Services and Databases

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.

Because databases provide powerful mechanisms for updating the


data they contain, they also provide integrated transaction support.
JavaSpaces technology, on the other hand, use a Jini technology
transaction service, which is provided externally, if transactions are
required.

JavaSpaces Technology 9-11


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Storing an Entry

Rules for Entry objects were introduced in the discussion on the


Lookup service in the ‘‘What Is an Entry Object?’’ section on page 6-
17. Entry objects must adhere to the following rules:

● Implement net.jini.core.entry.Entry

● Extend Serializable

● Use net.jini.entry.AbstractEntry

● Require zero argument constructor

You also saw that the attributes must be the following:

● public

● Serializable

● Not transient

● Not final

● References

9-12 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The reasons for these restrictions are rooted in the way the Entry
objects are stored, and the way they are matched and retrieved in a
space.

When an Entry is placed in a space, it is first converted to a serialized


form. In this form, each member of the object is serialized individually;
the object is not serialized as a whole in the conventional way. This is
done to allow template matching to be performed on a field-by-field
basis, and to allow null fields in the template to be wildcards.

This modified serialized storage format is the origin of the


requirements that were outlined previously. When an Entry is
reconstituted from its stored form, the space constructs an
uninitialized object of the entry’s type, and then initializes the
individual fields from the stored object. For this to work successfully,
there must be a zero-argument constructor. For the initialization to
work, each field must be public and non-final, otherwise the space
cannot to write to the field. The field must be a serializable reference
type; that is, not a primitive. The field must also be non-transient;
otherwise it will be abandoned before the Entry is transmitted over
the network to the JavaSpaces technology software.

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.

JavaSpaces Technology 9-13


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

JavaSpace Interface Methods

Each of these four methods attempts to locate an entry in the space.


Entries are qualified by matching the supplied template (the first
argument to each method). An entry matches the template if the entry
in the space is an instance of the defining class for the template entry
and each non-null field in the template entry matches the
corresponding field in the stored entry.

This form of matching allows a subclass to be returned and individual


fields to be ignored when making the content comparisons, but does
not allow you to use any kind of ranges or other expressions (such as
"greater than Aardvark").

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

9-14 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
entries. However, this is a design issue; if you need to perform such an
operation, then either your entry has been incorrectly designed, or
your design uses JavaSpaces services incorrectly.

The read operations return a copy of an entry that matches the


template, but leave the object in the store. By contrast, the take
operations remove the entry from the store.

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.

In all cases, the second argument, the transaction, describes a grouping


of multiple operations that must either be entirely successful or
entirely unwound. Therefore, if an entry is taken from the space under
a transaction that subsequently fails, the space behaves as if the entry
was never removed from it. A null transaction argument implies that
the method is unconditional.

JavaSpaces Technology 9-15


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

JavaSpace Interface Methods

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.

The notify method requests that remote events be issued when a


matching entry is written into the space. This registration is leased (the
lease is part of the EventRegistration object that is the method
return value). The long argument specifies a requested lease time for
this registration. The MarshalledObject provides the handback
object for the event. This handback object was discussed in the
‘‘Dispatching Events’’ section on page 5-8.

As with all the JavaSpace interface methods, you can apply a


transaction to this. When the transaction completes, the event
registration is cancelled.

9-16 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Sometimes it is necessary to pass the same Entry object across many
calls to a JavaSpaces technology service. This can be expensive in
terms of network bandwidth. To help alleviate this situation, the
snapshot method allows a space to provide a small object that is
effectively a shorthand for a larger one. If it is used in any method call,
for example, as the template of a read or notify call, the space reacts as
if the original entry had been provided instead. You can use snapshot
Entry objects only with the space that created them, they are not
interchangeable if you have multiple JavaSpaces technology services
running.

JavaSpaces Technology 9-17


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9

Example Using JavaSpaces Technology Services

This example demonstrates the use of JavaSpaces technology in the


role of distributed inter-process communication. The example allows a
simple compute job to be submitted from a client to a server, and have
the server return the completed job back to the client.

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.

9-18 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The overall flow of work is that the server is waiting to read a job from
the space, while the clients put work into the space from time to time.
After a server has taken a job out of the space and executed it, the
server puts the completed job back into the space. The client, which
has been waiting for the completed job to return, takes the job out at
this point.

To achieve this, you must address a number of problems. A job must


be recognizable. This example uses a variation of the Runnable
interface. There must be a way to distinguish a job that is awaiting
execution from one that has been completed. Finally, there must be a
way for a client to recognize its own job when it has been completed
and returned to the space.

JavaSpaces Technology 9-19


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The RunnableEntry Class

The following is an example of the code for the RunnableEntry class.


1 import java.io.Serializable;
2 import net.jini.core.lookup.ServiceID;
3 import net.jini.entry.AbstractEntry;
4
5 public class RunnableEntry
6 extends AbstractEntry
7 implements Runnable {
8
9 public static final Integer AWAITING_EXECUTION = new Integer(0);
10 public static final Integer EXECUTION_COMPLETE = new Integer(1);
11
12 // run method implementation should set this to EXECUTION_COMPLETE
13 public Integer state = AWAITING_EXECUTION;
14
15 // used to uniquely identify this ’job’
16 public ServiceID id;
17
18 // store returned data here:
19 public Serializable data;
20
21 public void run() {
22 state = EXECUTION_COMPLETE;
23 }
24 }
Code 9-1 RunnableEntry.java

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.

9-20 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The MPCClient Class

The following is an example of the code for the MPCClient class.


1 import java.net.InetAddress;
2 import java.net.UnknownHostException;
3 import net.jini.space.JavaSpace;
4 import net.jini.core.discovery.LookupLocator;
5 import net.jini.core.lookup.ServiceRegistrar;
6 import net.jini.core.lookup.ServiceTemplate;
7 import net.jini.core.lease.Lease;
8 import net.jini.core.lookup.ServiceID;
9
10 public class MPCClient {
11
12 private JavaSpace space;
13
14 public MPCClient(JavaSpace space) {
15 this.space = space;
16 }
17
18 public void submit(RunnableEntry r) {
19 RunnableEntry template = new RunnableEntry();
20 template.run(); // want to recognize completed tasks
21
22 long localIP1 = 0;
23 try {
24 byte [] localIP = InetAddress.getLocalHost().getAddress();
25 localIP1 = (localIP[0] << 24) + (localIP[1] << 16) +
26 (localIP[2] << 8) + (localIP[3]);
27 }
28 catch (UnknownHostException ex) {
29 }
30 long partRandom = (Double.doubleToLongBits(Math.random()) &
31 0xffffffff00000000L) + localIP1;
32 r.id = new ServiceID(System.currentTimeMillis(), partRandom);
33 template.id = r.id; // want to recognize this job only
34
35 try {
36 space.write(r, null, Lease.FOREVER);
37 System.out.println("Submitted a job");
38
39 r = (RunnableEntry)(space.take(template, null, Long.MAX_VALUE));
40 System.out.println("Got job back completed : " + r);
41 }

JavaSpaces Technology 9-21


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
42 catch(net.jini.core.transaction.TransactionException tex) {
43 tex.printStackTrace();
44 }
45 catch(java.rmi.RemoteException rmiex) {
46 rmiex.printStackTrace();
47 }
48 catch(java.lang.InterruptedException intex) {
49 intex.printStackTrace();
50 }
51 catch(net.jini.core.entry.UnusableEntryException ueeex) {
52 ueeex.printStackTrace();
53 }
54 }
55 // PageBreak
56 public static void main(String args[]) throws Throwable {
57 LookupLocator ll = new LookupLocator(args[0]);
58 ServiceRegistrar reg = ll.getRegistrar();
59 Class [] classes = { JavaSpace.class };
60 ServiceTemplate templ = new ServiceTemplate(null, classes, null);
61 JavaSpace space = (JavaSpace)(reg.lookup(templ));
62 MPCClient mpcc = new MPCClient(space);
63 for (int i = 1; i < args.length; i++) {
64 Class c = Class.forName(args[i]);
65 RunnableEntry re = (RunnableEntry)(c.newInstance());
66 mpcc.submit(re);
67 }
68 System.exit(0);
69 }
70 }
Code 9-2 MPCClient.java

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.

Inside the submit method, two instances of the RunnableEntry


class are built. One is the actual job; this is of the class specified on the
command line. The other is a template that is used by the client to
retrieve the job from the space. In the retrieval template, the job ID is
set to a value that is intended to be globally unique to this job. The
same ID is set in the actual job. The retrieval template is also set to the
EXECUTION_COMPLETE state, so that the job is read back from the
space only after it is executed.

9-22 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
From a design point of view, the bulk of the client’s work is simply to
write the job into the space, and then wait until it can read the job back
in a completed form.

JavaSpaces Technology 9-23


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The MPC Class

The following is an example of the code for the MPC class.


1 import net.jini.space.JavaSpace;
2 import net.jini.core.discovery.LookupLocator;
3 import net.jini.core.lookup.ServiceRegistrar;
4 import net.jini.core.lookup.ServiceTemplate;
5 import net.jini.core.lease.Lease;
6
7 public class MPC {
8
9 private static final RunnableEntry template = new RunnableEntry();
10 private JavaSpace space;
11
12 public MPC(JavaSpace space) {
13 this.space = space;
14 }
15
16 public void run() {
17 for (;;) {
18 try {
19 RunnableEntry r =
20 (RunnableEntry)(space.take(template, null, Long.MAX_VALUE));
21 System.out.println("Got a job");
22
23 r.run();
24 System.out.println("Ran the job");
25 space.write(r, null, Lease.FOREVER);
26 System.out.println("Put the job back");
27 }
28 catch(net.jini.core.transaction.TransactionException tex) {
29 tex.printStackTrace();
30 }
31 catch(java.rmi.RemoteException rmiex) {
32 rmiex.printStackTrace();
33 }
34 catch(java.lang.InterruptedException intex) {
35 intex.printStackTrace();
36 }
37 catch(net.jini.core.entry.UnusableEntryException ueeex) {
38 ueeex.printStackTrace();
39 }
40 }
41 }

9-24 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
42
43 public static void main(String args[]) throws Throwable {
44 LookupLocator ll = new LookupLocator(args[0]);
45 ServiceRegistrar reg = ll.getRegistrar();
46 Class [] classes = { JavaSpace.class };
47 ServiceTemplate templ = new ServiceTemplate(null, classes, null);
48 JavaSpace space = (JavaSpace)(reg.lookup(templ));
49 MPC mpc = new MPC(space);
50 mpc.run();
51 }
52 }
Code 9-3 MPC.java

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.

JavaSpaces Technology 9-25


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
The Jobs

The following code examples demonstrate different tasks.


1 public class RunnableOne extends RunnableEntry {
2 public RunnableOne() {
3 data = new Integer(0);
4 }
5
6 public void run() {
7 super.run();
8 System.out.println("Hello, I’m a "RunnableOne"");
9 data = new Integer(((Integer)data).intValue() + 1);
10 }
11
12 public String toString() {
13 return "I’m a "RunnableOne" that’s run " +
14 data + " times";
15 }
16 }
Code 9-4 RunnableOne.java

1 public class RunnableTwo extends RunnableEntry {


2 public void run() {
3 super.run();
4 System.out.println(toString());
5 }
6
7 public String toString() {
8 return "Hello, I’m a "RunnableTwo"";
9 }
10 }
Code 9-5 RunnableTwo.java

1 public class RunnableThree extends RunnableEntry {


2 public RunnableThree() {
3 int [] values = new int[2];
4 values[0] = 27;
5 values[1] = 9;
6
7 public void run() {
8 super.run();
9 int [] values = (int [])data;
10 int result = values[0] / values[1];

9-26 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
11 data = new Integer(result);
12 System.out.println("Calculation shows that " +
13 values[0] + " divided by " + values[1] +
14 " gives " + result);
15 }
16
17 public String toString() {
18 return "A "RunnableThree" containing " + data;
19 }
20 }
Code 9-6 RunnableThree.java

These three classes, RunnableOne, RunnableTwo, and RunnableThree,


demonstrate trivial jobs. RunnableOne and RunnableThree use the
data field to store results for return to the caller. This is not
mandatory, but remember that non-public fields are not stored in a
space. In the case of RunnableThree, the data field is used twice,
once to carry the inbound data and then later to carry the result of the
computation.

JavaSpaces Technology 9-27


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Exercise: Transactions and Spaces

Exercise objective – Create a job queue using a space that is protected


against server failure by transactions.

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.

9-28 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Exercise Summary
Discussion – Take a few minutes to discuss what experiences, issues,
or discoveries you had during the lab exercises.

● Experiences

● Interpretations

● Conclusions

● Applications

JavaSpaces Technology 9-29


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ State the strengths of the JavaSpaces technology, and contrast it


with databases

❑ List the requirements for an Entry in a space.

❑ Write code to use the methods of the JavaSpace interface

❑ Implement an anonymous inter-process communication scheme


using spaces.

9-30 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
9
Think Beyond

● What is the effect of transaction time-out on space operations?

● How does this interact with the operation’s own time-outs?

● How might using notification instead of time-outs on read/take


change this?

JavaSpaces Technology 9-31


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Common Pitfalls A

Objectives
Upon completion of this module, you should be able to:

● Avoid many of the most common mistakes in RMI and Jini


technology systems

● Recognize the key error messages caused by common mistakes

A-1
Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A
Relevance

Discussion – What mistakes have you made as you worked through


your lab exercises? Did any occur repeatedly? Do you understand the
reason for all the error messages you saw?

A-2 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A

Enabling Class Loading

If you need to download classes, you must install a security manager.


Always ensure you have System.setSecurityManager(new
SecurityManager()); near the start of your main method. If you fail
to do this, you will get unusual exceptions, typically class not found
exceptions, because the RMI system refuses to download classes under
these conditions. The error report might describe the consequence of
that refusal, not the refusal itself.

Because, in most cases, you must run with a security manager


installed, make sure you have granted enough permissions. In a
development environment, you might find it easiest to grant full
permissions until you are reasonably confident of your system as a
whole. Again, permission-denied exceptions can sometimes be
obscure, or even hidden entirely by their consequences.

Common Pitfalls A-3


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A

Enabling Object Loading

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.

As before, the exceptions generated when classes are not serializable


are not always obvious.

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;

A-4 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A
otherwise, the URL might not be meaningful in the context of the
client. Similarly, classes specified by a URL must be accessible to all
clients. Be aware that clients running on the far side of the firewall
might have difficulty in this respect.

Again, obscure exceptions can result in classes not being available for
download.

Common Pitfalls A-5


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A

Service Requirements

Jini technology services must be Serializable. If they are not, you


will find that the exceptions do not always point to the source of the
problem. In particular, you might find that lookup calls on the
ServiceRegistrar object return service objects in which the
service field is null.

Not every object in the Java programming language library is


serializable. Particular elements of the Abstract Window Toolkit and
Swing might not serialize correctly, or at all. Under these conditions,
you have a number of approaches available to you.

A-6 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A
You can define a special interface that defines the construction method
which, when called, creates the non-serializable elements of the object.
This approach works well with user interfaces because most of the
runtime information in a user interface does not need to be serialized.
For example, information describing the width and height of a button
should not be serialized, because it is best to redefine the object when
it is deserialized. Another approach would be to take over control of
serialization explicitly, either by using the Externalizable interface,
or by overriding the readObject and writeObject protected
methods. This approach requires less cooperation from clients and a
full understanding of the serialization system. You could also mark
some member variables as transient, and write checking code where
appropriate to reconstruct those items when they are null.

Common Pitfalls A-7


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A

Attribute and Entry Requirements

The attributes associated with Jini technology services must


implement the Entry interface. To do this correctly, they must be
serializable and have constructors that accept zero arguments.

You might be tempted to use inner classes when implementing


attributes. Be particularly careful here, because any nonstatic inner
class cannot have a zero argument constructor. This is because,
internally, an additional argument is created by the compiler. This
argument carries a reference to the outer class into the constructor for
the inner class. Consequently, inner classes do not make good
contenders for attributes or any other classes required to implement
the entry interface.

A-8 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A

Multicast Issues

Not all routers forward multicast packets. Most routers are


configurable in this respect, but, for reasons of security and
bandwidth, it is quite common to disable this feature. Normal,
undirected, discovery of a Jini Lookup service uses Multicast
protocols, and therefore, will fail across such routers. For this reason,
you must ensure that your programs can locate explicit Jini technology
Lookup services using Unicast Discovery protocols, which you can
configure from the command line, as well as normal Discovery
protocols.

The time to live on the multicast packets determines how many


routers a package can pass through before it is abandoned. In Jini
technology, the default value for this is 15. You can configure this
using the property net.jini.discovery.ttl. Fifteen is a large value,
which is probably sufficient to get from almost anywhere in the world
to almost anywhere else. In the development environment, reduce this
value according to the number of routers you must pass through.

Common Pitfalls A-9


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
A
Check Your Progress

Before continuing on to the next module, check that you are able to
accomplish or answer the following:

❑ Avoid many of the most common mistakes in RMI and Jini


technology systems

❑ Recognize the key error messages caused by common mistakes

A-10 Programming Distributed Services With Jini Technology


Copyright 1999 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services October 1999, Revision A
Copyright 1999 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits
réservés.
Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la
copie, la distribution, et la décompilation. Aucune partie de ce produit ou document ne peut être reproduite sous aucune
forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.
Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un
copyright et licencié par des fournisseurs de Sun.
Des parties de ce produit pourront être dérivées du systèmes Berkeley 4.3 BSD licenciés par l’Université de Californie.
UNIX est une marque déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company Ltd.
Sun, Sun Microsystems, le logo Sun, Solaris, Java, JDK, JavaBeans, le Java Logo, 100% Pure Java, Jini, et JavaSpaces sont
des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays.
L’interfaces d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses
utilisateurs et licenciés. Sun reconnaît les efforts de pionniers de Xerox pour larecherche et le développement du concept
des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive
de Xerox sur l’interface d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent
en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux licences écrites de Sun.
L’accord du gouvernement américain est requis avant l’exportation du produit.
Le système X Window est un produit de X Consortium, Inc.
Postscript est de marque de fabrique de Adobe Systems Incorporated.
LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET
GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA
LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE
MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

Please
Recycle

You might also like