Remote method invocation (RMI) technology was first introduced in JDK 1.1. It elevates the average Java develo!er to an entirely new!aradigm%%the world of distri#uted o#&ect com!uting.
Remote method invocation (RMI) technology was first introduced in JDK 1.1. It elevates the average Java develo!er to an entirely new!aradigm%%the world of distri#uted o#&ect com!uting.
Remote method invocation (RMI) technology was first introduced in JDK 1.1. It elevates the average Java develo!er to an entirely new!aradigm%%the world of distri#uted o#&ect com!uting.
Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates networ !rogramming to a higher !lane. "lthough RMI is relatively easy to use, it is a remara#ly !owerful technology and e$!oses the average Java develo!er to an entirely new !aradigm%%the world of distri#uted o#&ect com!uting. 'his course !rovides you with an in%de!th introduction to this versatile technology. RMI has evolved considera#ly since JDK 1.1, and has #een significantly u!graded under the Java ( )DK. *here a!!lica#le, the differences #etween the two releases will #e indicated. Goals " !rimary goal for the RMI designers was to allow !rogrammers to develo! distri#uted Java !rograms with the same synta$ and semantics used for non%distri#uted !rograms. 'o do this, they had to carefully ma! how Java classes and o#&ects wor in a single Java +irtual Machine 1 (J+M) to a new model of how classes and o#&ects would wor in a distri#uted (multi!le J+M) com!uting environment. 'his section introduces the RMI architecture from the !ers!ective of the distri#uted or remote Java o#&ects, and e$!lores their differences through the #ehavior of local Java o#&ects. 'he RMI architecture defines how o#&ects #ehave, how and when e$ce!tions can occur, how memory is managed, and how !arameters are !assed to, and returned from, remote methods. Comparison of Distributed and Nondistributed Java Programs 'he RMI architects tried to mae the use of distri#uted Java o#&ects similar to using local Java o#&ects. *hile they succeeded, some im!ortant differences are listed in the ta#le #elow. Do not worry if you do not understand all of the difference. 'hey will #ecome clear as you e$!lore the RMI architecture. ,ou can use this ta#le as a reference as you learn a#out RMI. -ocal .#&ect Remote .#&ect .#&ect Definition " local o#&ect is defined #y a Java class. " remote o#&ect/s e$!orted #ehavior is defined #y an interface that must e$tend the Remote interface. .#&ect Im!lementation " local o#&ect is im!lemented #y its Java class. " remote o#&ect/s #ehavior is e$ecuted #y a Java class that im!lements the remote interface. 1 .#&ect 0reation " new instance of a local o#&ect is created #y the new o!erator. " new instance of a remote o#&ect is created on the host com!uter with the new o!erator. " client cannot directly create a new remote o#&ect (unless using Java ( Remote .#&ect "ctivation). .#&ect "ccess " local o#&ect is accessed directly via an o#&ect reference varia#le. " remote o#&ect is accessed via an o#&ect reference varia#le which !oints to a !ro$y stu# im!lementation of the remote interface. References In a single J+M, an o#&ect reference !oints directly at an o#&ect in the hea!. " 1remote reference1 is a !ointer to a !ro$y o#&ect (a 1stu#1) in the local hea!. 'hat stu# contains information that allows it to connect to a remote o#&ect, which contains the im!lementation of the methods. "ctive References In a single J+M, an o#&ect is considered 1alive1 if there is at least one reference to it. In a distri#uted environment, remote J+Ms may crash, and networ connections may #e lost. " remote o#&ect is considered to have an active remote reference to it if it has #een accessed within a certain time !eriod (the lease !eriod). If all remote references have #een e$!licitly dro!!ed, or if all remote references have e$!ired leases, then a remote o#&ect is availa#le for distri#uted gar#age collection. 2inali3ation If an o#&ect im!lements the finali3e() method, it is called #efore an o#&ect is reclaimed #y the gar#age collector. If a remote o#&ect im!lements the 4nreferenced interface, the unreferenced method of that interface is called when all remote references have #een dro!!ed. 5ar#age 0ollection *hen all local references to an o#&ect have #een dro!!ed, an o#&ect #ecomes a candidate for gar#age collection. 'he distri#uted gar#age collector wors with the local gar#age collector. If there are no remote references and all local references to a remote o#&ect have #een dro!!ed, then it #ecomes a candidate for gar#age collection through the normal means. 6$ce!tions 6$ce!tions are either Runtime e$ce!tions or 6$ce!tions. 'he Java com!iler forces a !rogram to handle all 6$ce!tions. RMI forces !rograms to deal with any !ossi#le Remote6$ce!tion o#&ects that may #e thrown. 'his was done to ensure the ro#ustness of distri#uted a!!lications. Java RMI Architecture ( 'he design goal for the RMI architecture was to create a Java distri#uted o#&ect model that integrates naturally into the Java !rogramming language and the local o#&ect model. RMI architects have succeeded7 creating a system that e$tends the safety and ro#ustness of the Java architecture to the distri#uted com!uting world. Interfaces !he "eart of RMI 'he RMI architecture is #ased on one im!ortant !rinci!le8 the definition of #ehavior and the im!lementation of that #ehavior are se!arate conce!ts. RMI allows the code that defines the #ehavior and the code that im!lements the #ehavior to remain se!arate and to run on se!arate J+Ms. 'his fits nicely with the needs of a distri#uted system where clients are concerned a#out the definition of a service and servers are focused on !roviding the service. )!ecifically, in RMI, the definition of a remote service is coded using a Java interface. 'he im!lementation of the remote service is coded in a class. 'herefore, the ey to understanding RMI is to remem#er that interfaces define behavior and classes define implementation. *hile the following diagram illustrates this se!aration, remem#er that a Java interface does not contain e$ecuta#le code. RMI su!!orts two classes that im!lement the same interface. 'he first class is the im!lementation of the #ehavior, and it runs on the server. 'he second class acts as a !ro$y for the remote service and it runs on the client. 'his is shown in the following diagram. 9 " client !rogram maes method calls on the !ro$y o#&ect, RMI sends the re:uest to the remote J+M, and forwards it to the im!lementation. "ny return values !rovided #y the im!lementation are sent #ac to the !ro$y and then to the client/s !rogram. RMI Architecture #a$ers *ith an understanding of the high%level RMI architecture, tae a loo under the covers to see its im!lementation. 'he RMI im!lementation is essentially #uilt from three a#straction layers. 'he first is the )tu# and )eleton layer, which lies &ust #eneath the view of the develo!er. 'his layer interce!ts method calls made #y the client to the interface reference varia#le and redirects these calls to a remote RMI service. 'he ne$t layer is the Remote Reference -ayer. 'his layer understands how to inter!ret and manage references made from clients to the remote service o#&ects. In JDK 1.1, this layer connects clients to remote service o#&ects that are running and e$!orted on a server. 'he connection is a one%to%one (unicast) lin. In the Java ( )DK, this layer was enhanced to su!!ort the activation of dormant remote service o#&ects via Remote Object Activation. 'he trans!ort layer is #ased on '0;<I; connections #etween machines in a networ. It !rovides #asic connectivity, as well as some firewall !enetration strategies. =y using a layered architecture each of the layers could #e enhanced or re!laced without affecting the rest of the system. 2or e$am!le, the trans!ort layer could #e re!laced #y a 4D;<I; layer without affecting the u!!er layers. %tub and %&eleton #a$er 'he stu# and seleton layer of RMI lie &ust #eneath the view of the Java develo!er. In this layer, RMI uses the ;ro$y design !attern as descri#ed in the #oo, Design Patterns #y 5amma, >elm, Johnson and +lissides. In the ;ro$y !attern, an o#&ect in one conte$t is re!resented #y another (the !ro$y) in a se!arate conte$t. 'he !ro$y nows how to forward method calls #etween the !artici!ating o#&ects. 'he following class diagram illustrates the ;ro$y !attern. ? In RMI/s use of the ;ro$y !attern, the stu# class !lays the role of the !ro$y, and the remote service im!lementation class !lays the role of the Real)u#&ect. " seleton is a hel!er class that is generated for RMI to use. 'he seleton understands how to communicate with the stu# across the RMI lin. 'he seleton carries on a conversation with the stu#7 it reads the !arameters for the method call from the lin, maes the call to the remote service im!lementation o#&ect, acce!ts the return value, and then writes the return value #ac to the stu#. In the Java ( )DK im!lementation of RMI, the new wire !rotocol has made seleton classes o#solete. RMI uses reflection to mae the connection to the remote service o#&ect. ,ou only have to worry a#out seleton classes and o#&ects in JDK 1.1 and JDK 1.1 com!ati#le system im!lementations. Remote Reference #a$er 'he Remote Reference -ayers defines and su!!orts the invocation semantics of the RMI connection. 'his layer !rovides a RemoteRef o#&ect that re!resents the lin to the remote service im!lementation o#&ect. 'he stu# o#&ects use the invoe() method in RemoteRef to forward the method call. 'he RemoteRef o#&ect understands the invocation semantics for remote services. 'he JDK 1.1 im!lementation of RMI !rovides only one way for clients to connect to remote service im!lementations8 a unicast, !oint%to%!oint connection. =efore a client can use a remote service, the remote service must #e instantiated on the server and e$!orted to the RMI system. (If it is the !rimary service, it must also #e named and registered in the RMI Registry). 'he Java ( )DK im!lementation of RMI adds a new semantic for the client%server connection. In this version, RMI su!!orts activata#le remote o#&ects. *hen a method call is made to the !ro$y for an activata#le o#&ect, RMI determines if the remote service im!lementation o#&ect is dormant. If it is dormant, RMI will instantiate the o#&ect and @ restore its state from a dis file. .nce an activata#le o#&ect is in memory, it #ehaves &ust lie JDK 1.1 remote service im!lementation o#&ects. .ther ty!es of connection semantics are !ossi#le. 2or e$am!le, with multicast, a single !ro$y could send a method re:uest to multi!le im!lementations simultaneously and acce!t the first re!ly (this im!roves res!onse time and !ossi#ly im!roves availa#ility). In the future, )un may add additional invocation semantics to RMI. !ransport #a$er 'he 'rans!ort -ayer maes the connection #etween J+Ms. "ll connections are stream% #ased networ connections that use '0;<I;. 6ven if two J+Ms are running on the same !hysical com!uter, they connect through their host com!uter/s '0;<I; networ !rotocol stac. ('his is why you must have an o!erational '0;<I; configuration on your com!uter to run the 6$ercises in this course). 'he following diagram shows the unfettered use of '0;<I; connections #etween J+Ms. "s you now, '0;<I; !rovides a !ersistent, stream%#ased connection #etween two machines #ased on an I; address and !ort num#er at each end. 4sually a DA) name is used instead of an I; address7 this means you could tal a#out a '0;<I; connection #etween flica.magelang.com89?@( and rosa.&guru.com8??9(. In the current release of RMI, '0;<I; connections are used as the foundation for all machine%to%machine connections. .n to! of '0;<I;, RMI uses a wire level !rotocol called Java Remote Method ;rotocol (JRM;). JRM; is a !ro!rietary, stream%#ased !rotocol that is only !artially s!ecified is now in two versions. 'he first version was released with the JDK 1.1 version of RMI and re:uired the use of )eleton classes on the server. 'he second version was released with the Java ( )DK. It has #een o!timi3ed for !erformance and does not re:uire seleton classes. (Aote that some alternate im!lementations, such as =6" *e#logic and Ain&aRMI do not use JRM;, #ut instead use their own wire level !rotocol. .#&ect)!ace/s +oyager does recogni3e JRM; and will intero!erate with RMI at the wire level.) )ome other changes with the Java ( )DK are that RMI service interfaces are not re:uired to e$tend from &ava.rmi.Remote and their service methods do not necessarily throw Remote6$ce!tion. B )un and I=M have &ointly wored on the ne$t version of RMI, called RMI%II.;, which will #e availa#le with Java ( )DK +ersion 1.9. 'he interesting thing a#out RMI%II.; is that instead of using JRM;, it will use the .#&ect Management 5rou! (.M5) Internet Inter%.R= ;rotocol, II.;, to communicate #etween clients and servers. 'he .M5 is a grou! of more than CDD mem#ers that defines a vendor%neutral, distri#uted o#&ect architecture called 0ommon .#&ect Re:uest =roer "rchitecture (0.R="). 0.R=" .#&ect Re:uest =roer (.R=) clients and servers communicate with each other using II.;. *ith the ado!tion of the .#&ects%#y%+alue e$tension to 0.R=" and the Java -anguage to ID- Ma!!ing !ro!osal, the ground wor was set for direct RMI to 0.R=" integration. 'his new RMI%II.; im!lementation su!!orts most of the RMI feature set, e$ce!t for8 &ava.rmi.server.RMI)ocet2actory 4nicastRemote.#&ect 4nreferenced 'he D50 interfaces 'he RMI trans!ort layer is designed to mae a connection #etween clients and server, even in the face of networing o#stacles. *hile the trans!ort layer !refers to use multi!le '0;<I; connections, some networ configurations only allow a single '0;<I; connection #etween a client and server (some #rowsers restrict a!!lets to a single networ connection #ac to their hosting server). In this case, the trans!ort layer multi!le$es multi!le virtual connections within a single '0;<I; connection. Naming Remote 'b(ects During the !resentation of the RMI "rchitecture, one :uestion has #een re!eatedly !ost!oned8 1>ow does a client find an RMI remote serviceE 1 Aow you/ll find the answer to that :uestion. 0lients find remote services #y using a naming or directory service. 'his may seem lie circular logic. >ow can a client locate a service #y using a serviceE In fact, that is e$actly the case. " naming or directory service is run on a well%nown host and !ort num#er. (Well-known meaning everyone in an organi3ation nowing what it is). RMI can use many different directory services, including the Java Aaming and Directory Interface (JADI). RMI itself includes a sim!le service called the RMI Registry, rmiregistry. 'he RMI Registry runs on each machine that hosts remote service o#&ects and acce!ts :ueries for services, #y default on !ort 1DFF. .n a host machine, a server !rogram creates a remote service #y first creating a local o#&ect that im!lements that service. Ae$t, it e$!orts that o#&ect to RMI. *hen the o#&ect G is e$!orted, RMI creates a listening service that waits for clients to connect and re:uest the service. "fter e$!orting, the server registers the o#&ect in the RMI Registry under a !u#lic name. .n the client side, the RMI Registry is accessed through the static class Aaming. It !rovides the method loou!() that a client uses to :uery a registry. 'he method loou!() acce!ts a 4R- that s!ecifies the server host name and the name of the desired service. 'he method returns a remote reference to the service o#&ect. 'he 4R- taes the form8
rmi8<<HhostInameJ K8HnameIserviceI!ortJL <HserviceInameJ where the hostIname is a name recogni3ed on the local area networ (-"A) or a DA) name on the Internet. 'he nameIserviceI!ort only needs to #e s!ecified only if the naming service is running on a different !ort to the default 1DFF. )sing RMI It is now time to #uild a woring RMI system and get hands%on e$!erience. In this section, you will #uild a sim!le remote calculator service and use it from a client !rogram. " woring RMI system is com!osed of several !arts. Interface definitions for the remote services Im!lementations of the remote services )tu# and )eleton files " server to host the remote services "n RMI Aaming service that allows clients to find the remote services " class file !rovider (an >''; or 2'; server) " client !rogram that needs the remote services In the ne$t sections, you will #uild a sim!le RMI system in a ste!%#y%ste! fashion. ,ou are encouraged to create a fresh su#directory on your com!uter and create these files as you read the te$t. 'o sim!lify things, you will use a single directory for the client and server code. =y running the client and the server out of the same directory, you will not have to set u! an >''; or 2'; server to !rovide the class files. (Details a#out how to use >''; and 2'; servers as class file !roviders will #e covered in the section on Distri#uting and Installing RMI )oftware) "ssuming that the RMI system is already designed, you tae the following ste!s to #uild a system8 C 1. *rite and com!ile Java code for interfaces (. *rite and com!ile Java code for im!lementation classes 9. 5enerate )tu# and )eleton class files from the im!lementation classes ?. *rite Java code for a remote service host !rogram @. Develo! Java code for RMI client !rogram B. Install and run RMI system *+ Interfaces 'he first ste! is to write and com!ile the Java code for the service interface. 'he 0alculator interface defines all of the remote features offered #y the service8
!u#lic interface 0alculator e$tends &ava.rmi.Remote M !u#lic long add(long a, long #) throws &ava.rmi.Remote6$ce!tion7
!u#lic long su#(long a, long #) throws &ava.rmi.Remote6$ce!tion7
!u#lic long mul(long a, long #) throws &ava.rmi.Remote6$ce!tion7
!u#lic long div(long a, long #) throws &ava.rmi.Remote6$ce!tion7 N Aotice this interface e$tends Remote, and each method signature declares that it may throw a Remote6$ce!tion o#&ect. 0o!y this file to your directory and com!ile it with the Java com!iler8 J&avac 0alculator.&ava ,+ Implementation Ae$t, you write the im!lementation for the remote service. 'his is the 0alculatorIm!l class8
F !u#lic class 0alculatorIm!l e$tends &ava.rmi.server.4nicastRemote.#&ect im!lements 0alculator M
<< Im!lementations must have an <<e$!licit constructor << in order to declare the <<Remote6$ce!tion e$ce!tion !u#lic 0alculatorIm!l() throws &ava.rmi.Remote6$ce!tion M su!er()7 N
!u#lic long add(long a, long #) throws &ava.rmi.Remote6$ce!tion M return a O #7 N
!u#lic long su#(long a, long #) throws &ava.rmi.Remote6$ce!tion M return a % #7 N
!u#lic long mul(long a, long #) throws &ava.rmi.Remote6$ce!tion M return a P #7 N
!u#lic long div(long a, long #) throws &ava.rmi.Remote6$ce!tion M return a < #7 N N "gain, co!y this code into your directory and com!ile it. 'he im!lementation class uses 4nicastRemote.#&ect to lin into the RMI system. In the e$am!le the im!lementation class directly e$tends 4nicastRemote.#&ect. 'his is not a re:uirement. " class that does not e$tend 4nicastRemote.#&ect may use its e$!ort.#&ect() method to #e lined into RMI. *hen a class e$tends 4nicastRemote.#&ect, it must !rovide a constructor that declares that it may throw a Remote6$ce!tion o#&ect. *hen this constructor calls 1D su!er(), it activates code in 4nicastRemote.#&ect that !erforms the RMI lining and remote o#&ect initiali3ation. -+ %tubs and %&eletons ,ou ne$t use the RMI com!iler, rmic, to generate the stu# and seleton files. 'he com!iler runs on the remote service implementation class file. Jrmic 0alculatorIm!l 'ry this in your directory. "fter you run rmic you should find the file 0alculatorI)tu#.class and, if you are running the Java ( )DK, 0alculatorI)el.class. .!tions for the JDK 1.1 version of the RMI com!iler, rmic, are8
4sage8 rmic Ho!tionsJ Hclass namesJ
where Ho!tionsJ includes8 %ee! Do not delete intermediate generated source files %ee!generated (same as 1%ee!1) %g 5enerate de#ugging info %de!end Recom!ile out%of%date files recursively %nowarn 5enerate no warnings %ver#ose .ut!ut messages a#out what the com!iler is doing %class!ath H!athJ )!ecify where to find in!ut source and class files %d HdirectoryJ )!ecify where to !lace generated class files %JHruntime flagJ ;ass argument to the &ava inter!reter 'he Java ( !latform version of rmic add three new o!tions8
%v1.1 0reate stu#s<seletons for JDK 1.1 stu# !rotocol version %vcom!at (default) 11 0reate stu#s<seletons com!ati#le with #oth JDK 1.1 and Java ( stu# !rotocol versions %v1.( 0reate stu#s for Java ( stu# !rotocol version only .+ "ost %erver Remote RMI services must #e hosted in a server !rocess. 'he class 0alculator)erver is a very sim!le server that !rovides the #are essentials for hosting.
im!ort &ava.rmi.Aaming7 !u#lic class 0alculator)erver M !u#lic 0alculator)erver() M try M 0alculator c Q new 0alculatorIm!l()7 Aaming.re#ind(1rmi8<<localhost81DFF<0alculator)ervice1, c)7 N catch (6$ce!tion e) M )ystem.out.!rintln(1'rou#le8 1 O e)7 N N !u#lic static void main()tring argsKL) M new 0alculator)erver()7 N N /+ Client 'he source code for the client follows8
!u#lic static void main()tringKL args) M try M 0alculator c Q (0alculator) Aaming.loou!( 1rmi8<<localhost <0alculator)ervice1)7 )ystem.out.!rintln( c.su#(?, 9) )7 )ystem.out.!rintln( c.add(?, @) )7 )ystem.out.!rintln( c.mul(9, B) )7 )ystem.out.!rintln( c.div(F, 9) )7 N catch (Malformed4R-6$ce!tion murle) M )ystem.out.!rintln()7 )ystem.out.!rintln( 1Malformed4R-6$ce!tion1)7 )ystem.out.!rintln(murle)7 N catch (Remote6$ce!tion re) M )ystem.out.!rintln()7 )ystem.out.!rintln( 1Remote6$ce!tion1)7 )ystem.out.!rintln(re)7 N catch (Aot=ound6$ce!tion n#e) M )ystem.out.!rintln()7 )ystem.out.!rintln( 1Aot=ound6$ce!tion1)7 )ystem.out.!rintln(n#e)7 N catch ( &ava.lang."rithmetic6$ce!tion ae) M )ystem.out.!rintln()7 )ystem.out.!rintln( 1&ava.lang."rithmetic6$ce!tion1)7 )ystem.out.!rintln(ae)7 N N N 0+ Running the RMI %$stem ,ou are now ready to run the systemR ,ou need to start three consoles, one for the server, one for the client, and one for the RMIRegistry. 19 )tart with the Registry. ,ou must #e in the directory that contains the classes you have written. 2rom there, enter the following8 rmiregistry If all goes well, the registry will start running and you can switch to the ne$t console. In the second console start the server hosting the 0alculator)ervice, and enter the following8 J&ava 0alculator)erver It will start, load the im!lementation into memory and wait for a client connection. In the last console, start the client !rogram. J&ava 0alculator0lient If all goes well you will see the following out!ut8
1 F 1C 9 'hat/s it7 you have created a woring RMI system. 6ven though you ran the three consoles on the same com!uter, RMI uses your networ stac and '0;<I; to communicate #etween the three se!arate J+Ms. 'his is a full%fledged RMI system. 12ercise 1. 4M- Definition of RMI 6$am!le )ystem (. )im!le =aning )ystem Parameters in RMI ,ou have seen that RMI su!!orts method calls to remote o#&ects. *hen these calls involve !assing !arameters or acce!ting a return value, how does RMI transfer these #etween J+MsE *hat semantics are usedE Does RMI su!!ort !ass%#y%value or !ass%#y% referenceE 'he answer de!ends on whether the !arameters are !rimitive data ty!es, o#&ects, or remote o#&ects. Parameters in a %ingle J3M 1? 2irst, review how !arameters are !assed in a single J+M. 'he normal semantics for Java technology is !ass%#y%value. *hen a !arameter is !assed to a method, the J+M maes a co!y of the value, !laces the co!y on the stac and then e$ecutes the method. *hen the code inside a method uses a !arameter, it accesses its stac and uses the co!y of the !arameter. +alues returned from methods are also co!ies. *hen a !rimitive data ty!e (#oolean, #yte, short, int, long, char, float, or dou#le) is !assed as a !arameter to a method, the mechanics of !ass%#y%value are straightforward. 'he mechanics of !assing an o#&ect as a !arameter are more com!le$. Recall that an o#&ect resides in hea! memory and is accessed through one or more reference varia#les. "nd, while the following code maes it loo lie an o#&ect is !assed to the method !rintln()
)tring s Q 1'est17 )ystem.out.!rintln(s)7 in the mechanics it is the reference varia#le that is !assed to the method. In the e$am!le, a co!y of reference varia#le s is made (increasing the reference count to the )tring o#&ect #y one) and is !laced on the stac. Inside the method, code uses the co!y of the reference to access the o#&ect. Aow you will see how RMI !asses !arameters and return values #etween remote J+Ms. Primitive Parameters *hen a !rimitive data ty!e is !assed as a !arameter to a remote method, the RMI system !asses it #y value. RMI will mae a co!y of a !rimitive data ty!e and send it to the remote method. If a method returns a !rimitive data ty!e, it is also returned to the calling J+M #y value. +alues are !assed #etween J+Ms in a standard, machine%inde!endent format. 'his allows J+Ms running on different !latforms to communicate with each other relia#ly. 'b(ect Parameters *hen an o#&ect is !assed to a remote method, the semantics change from the case of the single J+M. RMI sends the o#&ect itself, not its reference, #etween J+Ms. It is the object that is !assed #y value, not the reference to the o#&ect. )imilarly, when a remote method returns an o#&ect, a co!y of the whole o#&ect is returned to the calling !rogram. 4nlie !rimitive data ty!es, sending an o#&ect to a remote J+M is a nontrivial tas. " Java o#&ect can #e sim!le and self%contained, or it could refer to other Java o#&ects in com!le$ gra!h%lie structure. =ecause different J+Ms do not share hea! memory, RMI must send the referenced o#&ect and all o#&ects it references. (;assing large o#&ect gra!hs can use a lot of 0;4 time and networ #andwidth.) 1@ RMI uses a technology called Object Serialization to transform an o#&ect into a linear format that can then #e sent over the networ wire. .#&ect seriali3ation essentially flattens an o#&ect and any o#&ects it references. )eriali3ed o#&ects can #e de%seriali3ed in the memory of the remote J+M and made ready for use #y a Java !rogram. Remote 'b(ect Parameters RMI introduces a third ty!e of !arameter to consider8 remote o#&ects. "s you have seen, a client !rogram can o#tain a reference to a remote o#&ect through the RMI Registry !rogram. 'here is another way in which a client can o#tain a remote reference, it can #e returned to the client from a method call. In the following code, the =anManager service get"ccount() method is used to o#tain a remote reference to an "ccount remote service.
=anManager #m7 "ccount a7 try M #m Q (=anManager) Aaming.loou!( 1rmi8<<=an)erver <=anManager)ervice1 )7 a Q #m.get"ccount( 1&5uru1 )7 << 0ode that uses the account N catch (Remote6$ce!tion re) M N In the im!lementation of get"ccount(), the method returns a (local) reference to the remote service.
!u#lic "ccount get"ccount()tring accountAame) M << 0ode to find the matching account "ccountIm!l ai Q << return reference from search return ai7 N 1B *hen a method returns a local reference to an e$!orted remote o#&ect, RMI does not return that o#&ect. Instead, it su#stitutes another o#&ect (the remote !ro$y for that service) in the return stream. 'he following diagram illustrates how RMI method calls might #e used to8 Return a remote reference from )erver to 0lient " )end the remote reference from 0lient " to 0lient = )end the remote reference from 0lient = #ac to )erver Aotice that when the "ccountIm!l o#&ect is returned to 0lient ", the "ccount !ro$y o#&ect is su#stituted. )u#se:uent method calls continue to send the reference first to 0lient = and then #ac to )erver. During this !rocess, the reference continues to refer to one instance of the remote service. It is !articularly interesting to note that when the reference is returned to )erver, it is not converted into a local reference to the im!lementation o#&ect. *hile this would result in a s!eed im!rovement, maintaining this indirection ensures that the semantics of using a remote reference is maintained. 12ercise 9. RMI ;arameters RMI Client4side Callbac&s In many architectures, a server may need to mae a remote call to a client. 6$am!les include !rogress feed#ac, time tic notifications, warnings of !ro#lems, etc. 'o accom!lish this, a client must also act as an RMI server. 'here is nothing really s!ecial a#out this as RMI wors e:ually well #etween all com!uters. >owever, it may #e im!ractical for a client to e$tend &ava.rmi.server.4nicastRemote.#&ect. In these cases, a remote o#&ect may !re!are itself for remote use #y calling the static method 1G
4nicastRemote.#&ect.e$!ort.#&ect (HremoteIo#&ectJ) 12ercise ?. RMI 0lient 0all#acs Distributing and Installing RMI %oftware RMI adds su!!ort for a Distri#uted 0lass model to the Java !latform and e$tends Java technology/s reach to multi!le J+Ms. It should not #e a sur!rise that installing an RMI system is more involved than setting u! a Java runtime on a single com!uter. In this section, you will learn a#out the issues related to installing and distri#uting an RMI #ased system. 2or the !ur!oses of this section, it is assumed that the overall !rocess of designing a D0 system has led you to the !oint where you must consider the allocation of !rocessing to nodes. "nd you are trying to determine how to install the system onto each node. Distributing RMI Classes 'o run an RMI a!!lication, the su!!orting class files must #e !laced in locations that can #e found #y the server and the clients. 2or the server, the following classes must #e availa#le to its class loader8 Remote service interface definitions Remote service im!lementations )eletons for the im!lementation classes (JDK 1.1 #ased servers only) )tu#s for the im!lementation classes "ll other server classes 2or the client, the following classes must #e availa#le to its class loader8 Remote service interface definitions )tu#s for the remote service im!lementation classes )erver classes for o#&ects used #y the client (such as return values) "ll other client classes .nce you now which files must #e on the different nodes, it is a sim!le tas to mae sure they are availa#le to each J+M/s class loader. Automatic Distribution of Classes 'he RMI designers e$tended the conce!t of class loading to include the loading of classes from 2'; servers and >''; servers. 'his is a !owerful e$tension as it means that classes 1C can #e de!loyed in one, or only a few !laces, and all nodes in a RMI system will #e a#le to get the !ro!er class files to o!erate. RMI su!!orts this remote class loading through the RMI0lass-oader. If a client or server is running an RMI system and it sees that it must load a class from a remote location, it calls on the RMI0lass-oader to do this wor. 'he way RMI loads classes is controlled #y a num#er of !ro!erties. 'hese !ro!erties can #e set when each J+M is run8 &ava K %DH;ro!ertyAameJQH;ro!erty+alueJ LO H0lass2ileJ 'he !ro!erty &ava.rmi.server.code#ase is used to s!ecify a 4R-. 'his 4R- !oints to a file8, ft!8, or htt!8 location that su!!lies classes for o#&ects that are sent from this J+M. If a !rogram running in a J+M sends an o#&ect to another J+M (as the return value from a method), that other J+M needs to load the class file for that o#&ect. *hen RMI sends the o#&ect via seriali3ation of RMI em#eds the 4R- s!ecified #y this !arameter into the stream, alongside of the o#&ect. ote! R"# does not send class files along with the serialized objects$ If the remote J+M needs to load a class file for an o#&ect, it loos for the em#edded 4R- and contacts the server at that location for the file. *hen the !ro!erty &ava.rmi.server.use0ode#ase.nly is set to true, then the J+M will load classes from either a location s!ecified #y the 0-"));"'> environment varia#le or the 4R- s!ecified in this !ro!erty. =y using different com#inations of the availa#le system !ro!erties, a num#er of different RMI system configurations can #e created. %losed. "ll classes used #y clients and the server must #e located on the J+M and referenced #y the 0-"));"'> environment varia#le. Ao dynamic class loading is su!!orted. Server based. " client a!!let is loaded from the server/s 0.D6=")6 along with all su!!orting classes. 'his is similar to the way a!!lets are loaded from the same >''; server that su!!orts the a!!let/s we# !age. %lient d&namic. 'he !rimary classes are loaded #y referencing the 0-"));"'> environment varia#le of the J+M for the client. )u!!orting classes are loaded #y the &ava.rmi.server.RMI0lass-oader from an >''; or 2'; server on the networ at a location s!ecified #y the server. 1F Server-d&namic. 'he !rimary classes are loaded #y referencing the 0-"));"'> environment varia#le of the J+M for the server. )u!!orting classes are loaded #y the &ava.rmi.server.RMI0lass-oader from an >''; or 2'; server on the networ at a location s!ecified #y the client. 'ootstrap client. In this configuration, all of the client code is loaded from an >''; or 2'; server across the networ. 'he only code residing on the client machine is a small #ootstra! loader. 'ootstrap server. In this configuration, all of the server code is loaded from an >''; or 2'; server located on the networ. 'he only code residing on the server machine is a small #ootstra! loader. 'he e$ercise for this section involves creating a #ootstra! client configuration. ;lease follow the directions carefully as different files need to #e !laced and com!iled within se!arate directories. 12ercise @. =ootstra! 6$am!le 5irewall Issues 2irewalls are inevita#ly encountered #y any networed enter!rise a!!lication that has to o!erate #eyond the sheltering confines of an Intranet. 'y!ically, firewalls #loc all networ traffic, with the e$ce!tion of those intended for certain 1well%nown1 !orts. )ince the RMI trans!ort layer o!ens dynamic socet connections #etween the client and the server to facilitate communication, the JRM; traffic is ty!ically #loced #y most firewall im!lementations. =ut lucily, the RMI designers had antici!ated this !ro#lem, and a solution is !rovided #y the RMI trans!ort layer itself. 'o get across firewalls, RMI maes use of >''; tunneling #y enca!sulating the RMI calls within an >''; ;.)' re:uest. Aow, e$amine how >''; tunneling of RMI traffic wors #y taing a closer loo at the !ossi#le scenarios8 the RMI client, the server, or #oth can #e o!erating from #ehind a firewall. 'he following diagram shows the scenario where an RMI client located #ehind a firewall communicates with an e$ternal server. (D In the a#ove scenario, when the trans!ort layer tries to esta#lish a connection with the server, it is #loced #y the firewall. *hen this ha!!ens, the RMI trans!ort layer automatically retries #y enca!sulating the JRM; call data within an >''; ;.)' re:uest. 'he >''; ;.)' header for the call is in the form8
htt!8<<hostname8!ort If a client is #ehind a firewall, it is im!ortant that you also set the system !ro!erty htt!.!ro$y>ost a!!ro!riately. )ince almost all firewalls recogni3e the >''; !rotocol, the s!ecified !ro$y server should #e a#le to forward the call directly to the !ort on which the remote server is listening on the outside. .nce the >'';%enca!sulated JRM; data is received at the server, it is automatically decoded and dis!atched #y the RMI trans!ort layer. 'he re!ly is then sent #ac to client as >'';%enca!sulated data. 'he following diagram shows the scenario when #oth the RMI client and server are #ehind firewalls, or when the client !ro$y server can forward data only to the well%nown >''; !ort CD at the server. (1 In this case, the RMI trans!ort layer uses one additional level of indirectionR 'his is #ecause the client can no longer send the >'';%enca!sulated JRM; calls to ar#itrary !orts as the server is also #ehind a firewall. Instead, the RMI trans!ort layer !laces JRM; call inside the >''; !acets and send those !acets to !ort CD of the server. 'he >''; ;.)' header is now in the form
htt!8<<hostname8CD<cgi%#in<&ava%rmiEforwardQH!ortJ 'his causes the e$ecution of the 05I scri!t, &ava%rmi.cgi, which in turn invoes a local J+M, un#undles the >''; !acet, and forwards the call to the server !rocess on the designated !ort. RMI JRM;%#ased re!lies from the server are sent #ac as >''; R6;-, !acets to the originating client !ort where RMI again un#undles the information and sends it to the a!!ro!riate RMI stu#. .f course, for this to wor, the &ava%rmi.cgi scri!t, which is included within the standard JDK 1.1 or Java ( !latform distri#ution, must #e !reconfigured with the !ath of the Java inter!reter and located within the we# server/s cgi%#in directory. It is also e:ually im!ortant for the RMI server to s!ecify the host/s fully%:ualified domain name via a system !ro!erty u!on startu! to avoid any DA) resolution !ro#lems, as8
&ava.rmi.server.hostnameQhost.domain.com Aote8 Rather than maing use of 05I scri!t for the call forwarding, it is more efficient to use a servlet im!lementation of the same. ,ou should #e a#le to o#tain the servlet/s source code from )un/s RMI 2"S. It should #e noted that notwithstanding the #uilt%in mechanism for overcoming firewalls, RMI suffers a significant !erformance degradation im!osed #y >''; tunneling. 'here are other disadvantages to using >''; tunneling too. 2or instance, your RMI a!!lication will no longer #e a#le to multi!le$ JRM; calls on a single connection, since it would now follow a discrete re:uest<res!onse !rotocol. "dditionally, using the &ava%rmi.cgi scri!t e$!oses a fairly large security loo!hole on your server machine, as now, the scri!t can redirect any incoming re:uest to any !ort, com!letely #y!assing your firewalling mechanism. Develo!ers should also note that using >''; tunneling !recludes RMI a!!lications from using call#acs, which in itself could #e a ma&or design constraint. 0onse:uently, if a client detects a firewall, it can always disa#le the default >''; tunneling feature #y setting the !ro!erty8 &ava.rmi.server.disa#le>tt!Qtrue Distributed Garbage Collection (( .ne of the &oys of !rogramming for the Java !latform is not worrying a#out memory allocation. 'he J+M has an automatic gar#age collector that will reclaim the memory from any o#&ect that has #een discarded #y the running !rogram. .ne of the design o#&ectives for RMI was seamless integration into the Java !rogramming language, which includes gar#age collection. Designing an efficient single% machine gar#age collector is hard7 designing a distri#uted gar#age collector is very hard. 'he RMI system !rovides a reference counting distri#uted gar#age collection algorithm #ased on Modula%9/s Aetwor .#&ects. 'his system wors #y having the server ee! trac of which clients have re:uested access to remote o#&ects running on the server. *hen a reference is made, the server mars the o#&ect as 1dirty1 and when a client dro!s the reference, it is mared as #eing 1clean.1 'he interface to the D50 (distri#uted gar#age collector) is hidden in the stu#s and seletons layer. >owever, a remote o#&ect can im!lement the &ava.rmi.server.4nreferenced interface and get a notification via the unreferenced method when there are no longer any clients holding a live reference. In addition to the reference counting mechanism, a live client reference has a lease with a s!ecified time. If a client does not refresh the connection to the remote o#&ect #efore the lease term e$!ires, the reference is considered to #e dead and the remote o#&ect may #e gar#age collected. 'he lease time is controlled #y the system !ro!erty &ava.rmi.dgc.lease+alue. 'he value is in milliseconds and defaults to 1D minutes. =ecause of these gar#age collection semantics, a client must #e !re!ared to deal with remote o#&ects that have 1disa!!eared.1 In the following e$ercise, you will have the o!!ortunity to e$!eriment with the distri#uted gar#age collector. 12ercise B. Distri#uted 5ar#age 0ollection %eriali6ing Remote 'b(ects *hen designing a system using RMI, there are times when you would lie to have the fle$i#ility to control where a remote o#&ect runs. 'oday, when a remote o#&ect is #rought to life on a !articular J+M, it will remain on that J+M. ,ou cannot 1send1 the remote o#&ect to another machine for e$ecution at a new location. RMI maes it difficult to have the o!tion of running a service locally or remotely. 'he very reason RMI maes it easy to #uild some distri#uted a!!lication can mae it difficult to move o#&ects #etween J+Ms. *hen you declare that an o#&ect im!lements the &ava.rmi.Remote interface, RMI will !revent it from #eing seriali3ed and sent #etween (9 J+Ms as a !arameter. Instead of sending the im!lementation class for a &ava.rmi.Remote interface, RMI su#stitutes the stu# class. =ecause this su#stitution occurs in the RMI internal code, one cannot interce!t this o!eration. 'here are two different ways to solve this !ro#lem. 'he first involves manually seriali3ing the remote o#&ect and sending it to the other J+M. 'o do this, there are two strategies. 'he first strategy is to create an .#&ectIn!ut)tream and .#&ect.ut!ut)tream connection #etween the two J+Ms. *ith this, you can e$!licitly write the remote o#&ect to the stream. 'he second way is to seriali3e the o#&ect into a #yte array and send the #yte array as the return value to an RMI method call. =oth of these techni:ues re:uire that you code at a level #elow RMI and this can lead to e$tra coding and maintenance com!lications. In a second strategy, you can use a delegation !attern. In this !attern, you !lace the core functionality into a class that8 Does not im!lement &ava.rmi.Remote Does im!lement &ava.io.)eriali3a#le 'hen you #uild a remote interface that declares remote access to the functionality. *hen you create an im!lementation of the remote interface, instead of reim!lementing the functionality, you allow the remote im!lementation to defer, or delegate, to an instance of the local version. Aow loo at the #uilding #locs of this !attern. Aote that this is a very sim!le e$am!le. " real%world e$am!le would have a significant num#er of local fields and methods.
<< ;lace functionality in a local o#&ect !u#lic class -ocalModel im!lements &ava.io.)eriali3a#le M !u#lic )tring get+ersionAum#er() M return 1+ersion 1.D17 N N Ae$t, you declare an &ava.rmi.Remote interface that defines the same functionality8
interface RemoteModelRef (? e$tends &ava.rmi.Remote M )tring get+ersionAum#er() throws &ava.rmi.Remote6$ce!tion7 N 'he im!lementation of the remote service acce!ts a reference to the -ocalModel and delegates the real wor to that o#&ect8
!u#lic class RemoteModelIm!l e$tends &ava.rmi.server.4nicastRemote.#&ect im!lements RemoteModelRef M -ocalModel lm7
!u#lic RemoteModelIm!l (-ocalModel lm) throws &ava.rmi.Remote6$ce!tion M su!er()7 this.lm Q lm7 N
<< Delegate to the local <<model im!lementation !u#lic )tring get+ersionAum#er() throws &ava.rmi.Remote6$ce!tion M return lm.get+ersionAum#er()7 N N 2inally, you define a remote service that !rovides access to clients. 'his is done with a &ava.r mi.Remote interface and an im!lementation8
interface RemoteModelMgr e$tends &ava.rmi.Remote M (@ RemoteModelRef getRemoteModelRef() throws &ava.rmi.Remote6$ce!tion7
-ocalModel get-ocalModel() throws &ava.rmi.Remote6$ce!tion7 N
!u#lic class RemoteModelMgrIm!l e$tends &ava.rmi.server.4nicastRemote.#&ect im!lements RemoteModelMgr M -ocalModel lm7 RemoteModelIm!l rmIm!l7
!u#lic RemoteModelMgrIm!l() throws &ava.rmi.Remote6$ce!tion M su!er()7 N
!u#lic RemoteModelRef getRemoteModelRef() throws &ava.rmi.Remote6$ce!tion M << -a3y instantiation of delgatee if (null QQ lm) M lm Q new -ocalModel()7 N
<< -a3y instantiation of <<Remote Interface *ra!!er if (null QQ rmIm!l) M rmIm!l Q new RemoteModelIm!l (lm)7 N
return ((RemoteModelRef) rmIm!l)7 N
!u#lic -ocalModel get-ocalModel() throws &ava.rmi.Remote6$ce!tion M << Return a reference to the (B <<same -ocalModel << that e$ists as the delagetee <<of the RMI remote << o#&ect wra!!er
<< -a3y instantiation of delgatee if (null QQ lm) M lm Q new -ocalModel()7 N
return lm7 N N 12ercises G. )eriali3ing Remote .#&ects8 )erver C. )eriali3ing Remote .#&ects8 0lient Mobile Agent Architectures 'he solution to the mo#ile com!uting agent using RMI is, at #est, a wor%around. .ther distri#uted Java architectures have #een designed to address this issue and others. 'hese are collectively called mobile agent architect(res. )ome e$am!les are I=M/s "glets "rchitecture and .#&ect)!ace/s +oyager )ystem. 'hese systems are s!ecifically designed to allow and su!!ort the movement of Java o#&ects #etween J+Ms, carrying their data along with their e$ecution instructions. Alternate Implementations 'his module has covered the RMI architecture and )un/s im!lementation. 'here are other im!lementations availa#le, including8 Ain&aRMI " free im!lementation #uilt at the 4niversity of 0alifornia, =ereley. Ain&a su!!orts the JDK 1.1 version of RMI, with e$tensions. =6" *e#logic )erver =6" *e#logic )erver is a high !erformance, secure "!!lication )erver that su!!orts RMI, Microsoft 0.M, 0.R=", and 6J= (6nter!rise Java=eans), and other services. +oyager .#&ect)!ace/s +oyager !roduct trans!arently su!!orts RMI along with a !ro!rietary D.M, 0.R=", 6J=, Microsoft/s D0.M, and transaction services. (G