This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• Java provides a monitor for Java provides a monitor for each object and classeach object and class• Unique lock for each object Unique lock for each object and classand class• Monitor controls access to Monitor controls access to synchronizedsynchronized code (method, code (method, block block
•block must specify objectblock must specify object• Unsynchronized code is not Unsynchronized code is not regulated by monitorregulated by monitor
The Class classThe Class class
Objects of this class, called class Objects of this class, called class descriptors, are automatically created by the descriptors, are automatically created by the JVM when a class (or interface) is loadedJVM when a class (or interface) is loaded Accessed by an Object’s getClass methodAccessed by an Object’s getClass method Can get the class’s name, superclass, interfacesCan get the class’s name, superclass, interfaces Can be locked for thread synchronization Can be locked for thread synchronization
purposespurposes A class lock is a lock on a class Class objectA class lock is a lock on a class Class object
You can get a lock on a class (actually, the You can get a lock on a class (actually, the class’s Class object) by creating a class’s Class object) by creating a synchronizedsynchronized staticstatic method method
Only one thread can execute a (any) Only one thread can execute a (any) synchronizedsynchronized staticstatic method at a time method at a time
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Distributed ComputingDistributed Computing
High-Level DefinitionHigh-Level Definition Pieces of some computation run on separate Pieces of some computation run on separate
processing units (potentially across a network)processing units (potentially across a network) Goal: as close to seamless distribution as Goal: as close to seamless distribution as
possiblepossible Minimize the code changes required to split apart an Minimize the code changes required to split apart an
application such that it runs in a distributed application such that it runs in a distributed environmentenvironment
Distributed Computing requires a modular designDistributed Computing requires a modular design
Distributed ObjectsDistributed Objects
Distributed computing (without objects) has been Distributed computing (without objects) has been around awhile, e.g.:around awhile, e.g.: Socket-based interprocess communication (IPC)Socket-based interprocess communication (IPC) Remote Procedure Calls (RPC)Remote Procedure Calls (RPC) Distributed Computing Environment (DCE)Distributed Computing Environment (DCE)
But objects can be distributed as wellBut objects can be distributed as well Common Object Request Broker Architecture (CORBA)Common Object Request Broker Architecture (CORBA) Microsoft OLE, COM/DCOM, Active-X, ???Microsoft OLE, COM/DCOM, Active-X, ??? Java RMIJava RMI
Granularity of Distributed ComputingGranularity of Distributed Computing
Coarse-grained distribution (more common by Coarse-grained distribution (more common by far)far) Single objects representing a client and a serverSingle objects representing a client and a server
Fine-grained distributionFine-grained distribution Potentially every object (e.g., a delivery, an airplane) Potentially every object (e.g., a delivery, an airplane)
is distributedis distributed There are key performance, modularity, There are key performance, modularity,
flexibility trade-offs to make when deciding on flexibility trade-offs to make when deciding on an appropriate degree of granularityan appropriate degree of granularity
Client-Server ModelClient-Server Model
Servers are providers of a serviceServers are providers of a service Data providers (files, databases, images, ...)Data providers (files, databases, images, ...) Computing providersComputing providers
Clients are users of a serviceClients are users of a service Generally think of clients being “in front of the Generally think of clients being “in front of the
human user”human user”
RMI Example: Deitel Chapter 20Weather
RMI Example: Deitel Chapter 20Weather
Use the National Weather Service Web site:Use the National Weather Service Web site: http://iwin.nws.noaa.gov/iwin/us/traveler.htmlhttp://iwin.nws.noaa.gov/iwin/us/traveler.html
RMI At-A-GlanceRMI At-A-Glance
Objects in one Java Virtual Machine (JVM) invoke Objects in one Java Virtual Machine (JVM) invoke the methods of objects in another JVMthe methods of objects in another JVM Invoking objects (clients) are often called local objectsInvoking objects (clients) are often called local objects Invoked objects (servers) are often called remote Invoked objects (servers) are often called remote
RMI - Not Just for NetworksRMI - Not Just for Networks
Local and remote objects can be on the Local and remote objects can be on the same machine (but in different processes)same machine (but in different processes)
Local and remote objects can be on Local and remote objects can be on different machines across a networkdifferent machines across a network
Note: a single Java program can contain Note: a single Java program can contain both client and server objectsboth client and server objects
Similar to Remote Procedure Call (RPC)Similar to Remote Procedure Call (RPC)
Java Interfaces: A Key IngredientJava Interfaces: A Key Ingredient
If a class implements an interface, then an object of that class If a class implements an interface, then an object of that class can be “cast” to that interface “type”can be “cast” to that interface “type”
Can declare an “object reference” that uses an interface Can declare an “object reference” that uses an interface instead of a class typeinstead of a class type
When “client code” invokes an interface method on this When “client code” invokes an interface method on this reference, the JVM (at run-time)reference, the JVM (at run-time) determines which class (that implements the interface) the reference determines which class (that implements the interface) the reference
really refers toreally refers to operates on the object of that classoperates on the object of that class
Polymorphism via interfaces!Polymorphism via interfaces! ““Client code” only needs to know about interface, not Client code” only needs to know about interface, not
Remote interfaceRemote interface describes server object’s behavior describes server object’s behavior Server object and its name are registered with a “lookup Server object and its name are registered with a “lookup
remote interface remote interface name of server objectname of server object
Client asks rmiregistry for server object (by name)Client asks rmiregistry for server object (by name) Client receives a Client receives a remote interface referenceremote interface reference::
proxy/“stub”/representative of remote server object proxy/“stub”/representative of remote server object Client invokes methods of remote interface on the remote Client invokes methods of remote interface on the remote
interface referenceinterface reference
Remote Interfaces Remote Interfaces
The declaration of behavior The declaration of behavior (the interface(the interface) is ) is different from implementation of behavior different from implementation of behavior (class)(class) Built separately (often by different programmers)Built separately (often by different programmers) Run separately (often on different machines)Run separately (often on different machines) Servers implement behavior and expose interfacesServers implement behavior and expose interfaces Clients rely on interfaces to invoke serversClients rely on interfaces to invoke servers
Associates server object instances with namesAssociates server object instances with names Runs on each server machineRuns on each server machine Uses port 1099 as a defaultUses port 1099 as a default Started by the rmiregistry utility programStarted by the rmiregistry utility program Accessed by the client to get a proxy (stub) to Accessed by the client to get a proxy (stub) to
the server objectthe server object
The Java RMI MechanismThe Java RMI Mechanism
RMI is built on top of (uses) the JVMRMI is built on top of (uses) the JVM Activates remote objectsActivates remote objects Manages and monitors communication connectionsManages and monitors communication connections Tracks invocable objectsTracks invocable objects Typically based on TCP socketsTypically based on TCP sockets
Stream-based, IP address (DNS name), port numberStream-based, IP address (DNS name), port number Uses unicast (point-to-point)Uses unicast (point-to-point) Is being extended to use Internet Inter-ORB Protocol (IIOP)Is being extended to use Internet Inter-ORB Protocol (IIOP)
Laying the foundation for greater CORBA compatibilityLaying the foundation for greater CORBA compatibility
Most of this happens “behind the scenes”Most of this happens “behind the scenes”
RMI Layered ArchitectureRMI Layered Architecture
Based on Based on http://developer.java.sun.com/developer/onlineTraining/rmi
Client Program Server Program
Stubs & Skeletons Stubs & Skeletons
Remote Reference Layer Remote Reference Layer
Transport Layer
RMIRMI
SystemSystem
Using RMIUsing RMI
Define interfacesDefine interfaces Implement serversImplement servers Build clients that use the serversBuild clients that use the servers Compile the pieces and run themCompile the pieces and run them
Server SideServer Side
The server class implements a remote The server class implements a remote interface interface A remote interface is one that extends the A remote interface is one that extends the
java.rmi.Remote interfacejava.rmi.Remote interface e.g., public interface myInterface extends Remotee.g., public interface myInterface extends Remote
java.rmi.Remote is a “tagging” interface (i.e., it java.rmi.Remote is a “tagging” interface (i.e., it has no methods, like the Serializable interface)has no methods, like the Serializable interface)
Each declared method throws Each declared method throws java.rmi.RemoteExceptionjava.rmi.RemoteException
Server Side (continued)Server Side (continued)
A server class typically extends A server class typically extends java.rmi.UnicastRemoteObjectjava.rmi.UnicastRemoteObject Could alternatively invoke java.rmi.UnicastRemoteObject static Could alternatively invoke java.rmi.UnicastRemoteObject static
exportObject() methodexportObject() method Either approach makes instances of the class known to the RMI Either approach makes instances of the class known to the RMI
networking/communications details for servernetworking/communications details for server also keeps JVM running while server “waits” for also keeps JVM running while server “waits” for
remote method callsremote method calls Constructor has to throw RemoteExceptionConstructor has to throw RemoteException
Generally also address security issues associated with Generally also address security issues associated with downloadable code (more later)downloadable code (more later)
Server Side (concluded)Server Side (concluded)
In main() (typically)In main() (typically) Create an instance of the class as neededCreate an instance of the class as needed Register the instance with the RMI Registry Register the instance with the RMI Registry
Use Naming.rebind(serverObjName, objRef) where Use Naming.rebind(serverObjName, objRef) where serverObjName is a concatenation of the hostname serverObjName is a concatenation of the hostname (or IP address) and a name by which clients will (or IP address) and a name by which clients will find the serverfind the server
Implement the server logic exactly as you Implement the server logic exactly as you would for any local classwould for any local class
RMI Example: Deitel Chapter 20Interactions
RMI Example: Deitel Chapter 20Interactions
sunny.jpgsunny.jpgsunny.jpgsunny.jpg
sunny.jpgsunny.jpg
RMI ServerRMI Server RMI ClientRMI Client
ImplementationImplementation
TemperatureServerImpl
Remote InterfaceRemote Interface
TemperatureServer
TemperatureClient
traveler.htmltraveler.htmlNational Weather Service Web SiteNational Weather Service Web Site
The National Weather Service changed the format of their Traveler's Forecast web page slightly. Make the following changes to the file TemperatureServerImpl.java to fix the problem:
Line 35 should be changed from
String separator = "</PRE><HR> <BR><PRE>";
to
String separator = "TAV12";
Line 58 should be changed from
while ( !inputLine.equals( "" ) ) {
to
while ( inputLine.length() > 28 ) {
Recompile the file and regenerate your stub file before running the server.
From http://www.deitel.comFrom http://www.deitel.com
Client SideClient Side
All a client JVM knows how to do is to make local All a client JVM knows how to do is to make local method invocationsmethod invocations Client objects invoke server objects via “stubs”Client objects invoke server objects via “stubs” A “stub” is a local proxy for a remote objectA “stub” is a local proxy for a remote object The stub knows how to deal with the RMI mechanismThe stub knows how to deal with the RMI mechanism The client code treats the proxy as if it The client code treats the proxy as if it werewere the remote the remote
objectobject Other than that, the client just has to know where to Other than that, the client just has to know where to
look for a remote object of a specific namelook for a remote object of a specific name
Client Side (concluded)Client Side (concluded)
Contact the registry to find the objectContact the registry to find the object Install a Security Manager as neededInstall a Security Manager as needed Find the remote object on the server ()Find the remote object on the server ()
Naming.lookup(serverObjName)Naming.lookup(serverObjName) Returns a ref to a Remote (an object that implements Returns a ref to a Remote (an object that implements
a Remote interface)a Remote interface) Make sure that what you get is what you want (i.e., Make sure that what you get is what you want (i.e.,
implements the desired interface)implements the desired interface) if (ref instanceof myInterrface) { }if (ref instanceof myInterrface) { }
Use it as desiredUse it as desired Be sure to do the above in a try - catch (to get Be sure to do the above in a try - catch (to get
ATLANTA ATLANTA PTCLDY 61/42 PTCLDY 72/47PTCLDY 61/42 PTCLDY 72/47
Process #1: rmiregistryProcess #1: rmiregistry
Process #2: serverProcess #2: server
Process #3: clientProcess #3: client
Compilation & ExecutionCompilation & Execution
Compilation:Compilation: Compile pieces as normal using javacCompile pieces as normal using javac
If client and server in separate directories, need class file provider If client and server in separate directories, need class file provider (http or ftp server)(http or ftp server)
Compile the server (a second time) using the RMI compiler Compile the server (a second time) using the RMI compiler rmicrmic Produces a stub class for the client (could be made available via a Produces a stub class for the client (could be made available via a
download)download)
Execution:Execution: 3 Processes:3 Processes:
rmiregistry rmiregistry serverserver clientclient
RMI Example: Deitel Chapter 20Class and File Dependencies
RMI Example: Deitel Chapter 20Class and File Dependencies
sunny.jpgsunny.jpgsunny.jpgsunny.jpg
sunny.jpgsunny.jpg
RMI ServerRMI Server RMI ClientRMI Client
traveler.htmltraveler.htmlNational Weather Service Web SiteNational Weather Service Web Site
RMI uses serialization to pack/unpack RMI uses serialization to pack/unpack arguments and return values (via a process arguments and return values (via a process known as marshalling)known as marshalling) All primitive types are serializableAll primitive types are serializable User-defined classes must:User-defined classes must:
Implement/extend the Serializable interfaceImplement/extend the Serializable interface Have a public null constructorHave a public null constructor Only have references to serializable objectsOnly have references to serializable objects
Static variables are not transmittedStatic variables are not transmitted
Ramifications of RMI SerializationRamifications of RMI Serialization
Local arguments and return values are passed by Local arguments and return values are passed by valuevalue If it has to be serialized to travel from one process If it has to be serialized to travel from one process
(JVM) to another, it is copied(JVM) to another, it is copied Remote objects passed to or returned from a remote Remote objects passed to or returned from a remote
object’s methodsobject’s methods Actually get a reference to the stub for that remote Actually get a reference to the stub for that remote
objectobject Thus get a pass-by-reference semantics for this caseThus get a pass-by-reference semantics for this case
What About Polymorphism?What About Polymorphism?
Serialization only works for data, not Serialization only works for data, not methodsmethods
We occasionally want server types of We occasionally want server types of mechanisms to invoke mechanisms we mechanisms to invoke mechanisms we create using polymorphism (e.g., the paint() create using polymorphism (e.g., the paint() method of a JFrame)method of a JFrame)
RMI supports the dynamic loading of codeRMI supports the dynamic loading of code
Dynamic Loading of CodeDynamic Loading of Code
Server side can accept unknown (at compile time) Server side can accept unknown (at compile time) subclasses as arguments to method invocationssubclasses as arguments to method invocations
Requires such a class to create a Requires such a class to create a codebasecodebase Tells the JVM where to get the code from (just like Tells the JVM where to get the code from (just like
moving applets around in the Web!)moving applets around in the Web!) Contains a URL that can be used to download the codeContains a URL that can be used to download the code All RMI does is annotate the serialized data with the All RMI does is annotate the serialized data with the
URLURL Is used to transmit stubs around as well as customized Is used to transmit stubs around as well as customized
codecode The client does not have to receive stubs ahead of timeThe client does not have to receive stubs ahead of time
Security IssuesSecurity Issues
RMI supports downloading code at runtimeRMI supports downloading code at runtime E.g., getting stubs, remote polymorphismE.g., getting stubs, remote polymorphism
RMI provides a SecurityManager to enable the RMI provides a SecurityManager to enable the use of downloadable codeuse of downloadable code Implements a rudimentary security policy (e.g., all Implements a rudimentary security policy (e.g., all
code signed by Bill can write to this directory)code signed by Bill can write to this directory) See system.getSecurityManager(), system. See system.getSecurityManager(), system.
setSecurityManager(), and class setSecurityManager(), and class RMISecurityManager for more detailsRMISecurityManager for more details
RMI Activation FrameworkRMI Activation Framework
Mechanism for starting server-side objects Mechanism for starting server-side objects from the client sidefrom the client side Activate remote objects when neededActivate remote objects when needed Deactivate them when not neededDeactivate them when not needed
Useful when:Useful when: Have rarely used remote objects Have rarely used remote objects Have many remote objectsHave many remote objects To reconstitute remote services after a crashTo reconstitute remote services after a crash
Requires special codeRequires special code
Some Notes About RMISome Notes About RMI
The distributed environment is more fragile (need to The distributed environment is more fragile (need to worry more about exceptions)worry more about exceptions) Network connections can go downNetwork connections can go down Remote machines can go downRemote machines can go down
Garbage collectionGarbage collection Remote references have a lease periodRemote references have a lease period If no local and no remote references, becomes a candidate for If no local and no remote references, becomes a candidate for
GCGC Invokes the unreferenced method of the Unreferenced interface Invokes the unreferenced method of the Unreferenced interface
(if implemented) vs finalize(if implemented) vs finalize
Some Notes About RMI (continued)Some Notes About RMI (continued)
A remote object can be richer than the interface it presents to A remote object can be richer than the interface it presents to the outside worldthe outside world Not all of its methods have to be exposedNot all of its methods have to be exposed
A remote object can expose multiple sets of interfacesA remote object can expose multiple sets of interfaces E.g., an admin interface and a functional interfaceE.g., an admin interface and a functional interface
Higher parts of inheritance hierarchies can be remotedHigher parts of inheritance hierarchies can be remoted Base classes become serversBase classes become servers
Java does not use a separate Interface Definition Language Java does not use a separate Interface Definition Language (IDL)(IDL) JAVA RMI is specific to JavaJAVA RMI is specific to Java
Java does not use an Object Request Broker (ORB)Java does not use an Object Request Broker (ORB) Some typical ORB services are built into the RMI mechanism (e.g., Some typical ORB services are built into the RMI mechanism (e.g.,