distributed applications in java n.
Skip this Video
Loading SlideShow in 5 Seconds..
Distributed Applications in Java PowerPoint Presentation
Download Presentation
Distributed Applications in Java

Distributed Applications in Java

263 Views Download Presentation
Download Presentation

Distributed Applications in Java

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Distributed Applications in Java CS 420 – Spring 2006

  2. Outline • Distributed Applications in Java • Introduction to Distributed Computing • Java Object Serialization • Java Remote Method Invocation (RMI) • Introduction to Enterprise Java Beans (EJB) • Architecture • Types of EJBs • Enterprise Attributes • Putting it all Together

  3. Introduction to Distributed Computing

  4. Basic Concepts • Client-Server: • The client is the entity accessing the remote resource and the server provides access to the resource. Operationally, the client is the caller and the server is the callee. • In Java terms: • The client is the invoker of the method and the server is the object implementing the method.

  5. Basic Concepts (continued) • The client and the server can be heterogeneous: • Different implementation languages • Different operating systems • The roles can be transient • The definition is with respect to a particular interaction. • Client and Server refer both to the code and the system on which the code is running

  6. Client Server Interactions Client Server F(x) { return 5; } 2 y= F(x) 1 3 4 • Send message to call F with parameter X • Receive message that F was called with the given parameter • Send message with the result of calling F • Receive message with the result of calling F Network

  7. Finding the Server • How does the client find a server? • One approach is a Name Service: • Associate a name with each server • When server starts, it registers with a naming service using the name • When the client wants to find the server, it asks the naming service • Naming service can itself be a server • How does the client find the naming server?

  8. Naming Services Name Server Client Server 1 2 F(x) { return 5; } 4 y= F(x) 3 5 6 Register "F" with name server Lookup "F" using name server Send message to call F with parameter X Receive message that F was called with the give parameter Send message with the result of calling F Receive message with the result of calling F Network

  9. Parameter Passing • Distribution complicates parameters passing • Parameters are passed via a message and not via a local stack • Issues include: • Different representations of primitive types • convert representation • Pointers are address space relative • Composite Types (e.g., structures) • embedded pointers • need to be flattened and reconstructed

  10. Marshaling/Unmarshaling • Marshaling: • done by client (i.e., caller) • packing the parameters into a message • flatten structures (e.g., objects) • perform representation conversions if necessary • also done by server (i.e., callee) for results • Unmarshaling: • done by receiver of message to extract parameters

  11. Parameter Passing Flow Client Server y= F(x) Marshal X Send Msg Receive Msg Unmarshal X F(x) { return 5; } Network Marshal Result Send Msg w/ Result Receive Msg w/ Result Unmarshal Result

  12. Stubs and Skeletons • Encapsulate marshaling and communication • Enable application code in both client and server to treat call as local • Stub is on the client • implements original interface • contains information to find the server • in an OO language, the stub object is a proxy for the real object • Skeleton is on the server • calls original routine

  13. Stubs and Skeletons: Flow Client Server F(x) { // stub Marshall X Send Msg F_skeleton() { Receive Msg Unmarshal X Call F(X) Marshal Result Send Msg w/ Result Network } Receive Result Msg Unmarshal Result }

  14. Where do Stubs and Skeletons come from? • Writing (un)marshaling code is bug-prone • communication code has many details • structure of code is very mechanical • Answer: • Stubs and Skeletons can be generated from a description of the code to be remotely invoked • A separate Interface Definition Language (IDL) • Description can be generated from code to be distributed

  15. Server Architecture • Servers can typically handle concurrent requests from multiple clients • Typically the same address spaces provides multiple interfaces • A common server architecture: • accept a request (i.e., a call from a client) • determine which routine is being invoked • dispatch request to a thread of execution • start the thread executing in the appropriate skeleton

  16. Server Architecture (continued) Server Clients Dispatcher Worker Threads Call f_skel f Call g_skel network g f g

  17. Java Object Serialization

  18. Goals of Serialization • Provide a means of writing/reading the state of an object to/from a stream • Preserve inter-object relationships • Enable marshaling/unmarshaling • Do not require per-class implementation • Allow per-class customization

  19. Serialization Basic Concepts • All primitive types can be saved in a stream • The class of an object to be saved in a stream must implement one of: • • • Externalizable allows a high degree of customization • Not discussed further • Not all standard Java classes are serializable • Classes that provided access to system resources are not serializable • most of*,*, etc.

  20. ObjectOutputStream • is used to save the state of an object • writeObject(Object o) method on the stream which writes the indicated object to the stream • traverses references to other objects • referenced objects must also be serializable • in event of a cycle an object is only written to stream once • default does not write static or transient data • write<Type>(<Type> t) methods support writing primitives to stream

  21. writeObject(B) ==> throws java.lang.Thread B java.util.Hashtable java.lang.String java.lang.Thread not serializable Traversing The Graph writeObject(A) ==> succeeds A java.util.Hashtable java.lang.Integer java.lang.String

  22. Serialization Example import*; import*; // . . . // Create the ObjectOutputStream Socket s = new Socket(host, port); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); // Call writeObject on the Stream to write a Date object oos.writeObject(new java.util.Date()); // Call writeInt to write an int oos.writeInt(3);

  23. ObjectInputStreams • is used to restore the state of an object • readObject() returns next object in the stream • creates a new object graph • structurally equivalent to the graph that was originally written to the stream • objects in graph are distinct from original graph, i.e., don't compare ==.

  24. Java Remote Method Invocation (RMI)

  25. What is RMI? • Java Remote Method Invocation is a mechanism that allows calls between objects in different JVMs • Basic concepts: • Remote Interface • defines the methods that a client can invoke on a server • Remote Object • an object whose methods can be invoked from another JVM • Remote Method Invocation • invoking a method of a remote interface on a remote object, i.e., inter-JVM call

  26. RMI Running Example • To motivate this discussion, we will use a simple running example of a count server. • server supports a single method, getCount(), that returns the number of times it has been called • client calls the method and displays the results Client Server call getCount inc. count display result

  27. Remote Interface • Extends java.rmi.Remote • java.rmi.Remote is an empty interface • Flags methods that can be called remotely • Client is coded to remote interface • Invoking a remote method uses normal Java syntax • All methods of a remote interface must throw java.rmi.RemoteException • Thrown when a remote invocation fails, e.g., a communications failure • Used in generating stubs and skeletons

  28. Remote Interface Client Server call getCount inc. count display result Sample Remote Interface public interface Count extends java.rmi.Remote { public int getCount() throws java.rmi.RemoteException; }

  29. Remote Interface Client Server call getCount Remote Object inc. count display result Remote Object • Implements a remote interface • Can add additional methods • Typically extends (a subclass of) java.rmi.server.RemoteObject • Client uses a stub to refer to remote object • Never access remote object directly

  30. Sample Implementation Class public class CountImpl extends java.rmi.server.UnicastRemoteObject implements Count { private int count; public CountImpl() throws java.rmi.RemoteException { super(); count = 0; } public int getCount() throws java.rmi.RemoteException { return count++; } // . . .

  31. RMI Parameter Passing • There are two types of parameters to consider • Remote objects, i.e., implement java.rmi.Remote • Non-remote objects • This applies both to inputs and return results

  32. Remote Objects as Parameters • The target receives a reference to the client stub implementing the remote interface • Enables access to unnamed remote objects • Client creates a remote object and passes it as a parameter on a remote method • Server returns a remote object as the result of a remote method • Enables peers and not just client-server • Client invokes a remote method, passing a remote object that it implements as a parameter • When server invokes a method on this parameter it is using a client stub, this results in a callback to original client

  33. Passing Non-Remote Objects as Parameters • Objects are passed by value • A copy of object is sent to the server • Java Object Serialization used to copy parameters: • Non-remote-object parameters of a remote interface must be Serializable • Use of Serialization gives different semantics than normal Java parameter passing: • given remote method: • Object identity(Object o) { return o; } • then: • o != remote.identity(o)

  34. RMI Stubs and Skeletons • Stubs and skeletons are mechanically generated, e.g., by rmic (RMI Compiler) • input is a class file containing a remote object, e.g., CountImpl.class • output is class files for stub and skeleton for the remote object • CountImpl_Stub and CountImpl_Skel • optionally can keep Java source files • stub class extends RemoteStub • stub thus has remote semantics for equals, toString and hashCode

  35. Lab Review (1) • The remote object's codebase is specified by the remote object's server by setting the java.rmi.server.codebase property. The RMI server registers a remote object, bound to a name, with the RMI registry. • The RMI client requests a reference to a named remote object. The reference (the remote object's stub instance) is what the client will use to make remote method calls to the remote object. • The RMI registry returns a reference (the stub instance) to the requested class. If the class definition for the stub instance can be found locally in the client's CLASSPATH , which is always searched before the codebase, the client will load the class locally. However, if the definition for the stub is not found in the client's CLASSPATH, the client will attempt to retrieve the class definition from the remote object's codebase.

  36. Lab Review (2) • The client requests the class definition from the codebase. The codebase the client uses is the URL that was annotated to the stub instance when the stub class was loaded by the registry. Back in step 1, the annotated stub for the exported object was then registered with the RMI registry bound to a name. • The class definition for the stub (and any other class(es) that it needs) is downloaded to the client. • Now the client has all the information that it needs to invoke remote methods on the remote object. The stub instance acts as a proxy to the remote object that exists on the server, the RMI client uses the remote object's codebase to execute code in another, potentially remote JVM.

  37. Starting the Server • Likewise the drive name may be required in the path. "file:///h:/" should work for this. (Note three front slashes, the drive letter, a colon, and another front slash.) The red slash is part of the path. This is particularly important if your source and class files are on a non-system drive, such as H: or M:.

  38. Lessons Learned • The drive name may be required in the path. "file:///h:/" should work for this. (Note three front slashes, the drive letter, a colon, and another front slash.) This is particularly important if your source and class files are on a non-system drive, such as H: or M:.

  39. RMI's Strengths • Relatively easy to develop a distributed application • But harder than a non-distributed application • No need to learn a separate language or object model • But need to learn subtle differences • A pure Java solution • "Write Once, Run Anywhere"

  40. RMI's Weaknesses • Loss of object identity • If an object is passed by value, a new copy of the object is created • Performance • If one is not very careful, the use of serialization can result in sending very large messages • Potential for Deadlock if Callbacks are used • System A makes a remote call to system B • B makes a callback to A • The thread that will process the callback in A is not the thread that made the original call to B • If A was holding a lock when it made the initial call, deadlock may result.

  41. Introduction to EJBs

  42. Why Enterprise JavaBeans? • Server side re-usable components that enable rapid application development • Factor out common services from application development • Distribution and remote invocation (interface with other services) • Transaction management (one unit of work) • Thread management • Persistence (related to database) • Security (JAAS) • Scalability • You can just concentrate on application code!

  43. The three types of Beans • Session Beans (~service layer) • Provide synchronous (request-response conversation) client access to business services • Can be stateless (shared) or stateful (one per client) • Have NO persistent state • Entity Beans • Represent persistent components in the business model (database tables and columns) • Students, employees, documents, etc. • Shared between clients, but access is synchronized • Message Driven Beans (not efficient for real-time) • Provide asynchronous access to business services (a queue) • Invoked by messages instead of distributed method call • Clients do not interact directly with them

  44. Stateless Session Beans • Execute on behalf of one client at a time • Re-entrant, executes logic that does not keep state across invocations • When done servicing one client, gets released so it can service another • A small pool of beans can be created to service many clients – scalable! • A client may make multiple concurrent invocations – each invocation will get a different instance from the pool to process the request

  45. Stateful Session Beans • Converse with clients across invocations and time • Are managed by one and only one client • Can not be switched between invocations • Can hold state of the conversation (like the contents of a shopping cart) • May be passivated (serialized, moved to secondary storage) as required • State may not be maintained across server restarts • Not as scalable, can only process one invocation at a time and may or may not be clustered • Note: should always have @remove annotation at the end.

  46. What is a Container? (application container) • The fundamental part of an EJB server • Manages the Beans • Deployment • Lifecycles – instantiation and pooling • Execution threads • All client access goes through it • Provides integration of services (naming, transactions, etc.) • Intercepts calls and injects the service infrastructure • Client invocations are decoupled through a proxy • The proxy routes all calls through the container • The service code is applied before the business code is executed (JBoss interceptors) • The container calls the bean implementation directly • Supplies the bean implementation with a EJBContext object which provides details of the environment and current invocation

  47. What is a Proxy? • Similar to a ‘middleman’, a person in the middle • Provides a “special” object which implements your business interface • The object is used as a replacement for the actual service implementation to “hide” the complexity • Marshalling the call parameters • Sending the invocation to the server • Injects the service code (transactions, etc.) • Calls the business logic • Completes the service code (commit) • Marshalls the return objects • Sends the response back to the client • Is the object bound into JNDI • Client never sees the bean implementation and does not have to! • JBoss dynamically builds proxy at deployment, other containers may require a separate static compilation step

  48. Deployment Descriptor ejb-jar.xml • Now optional in EJB3 • Can be used to complement or override information provided by annotations • Contains metadata for the beans • Type of bean • Name of class • Environment properties • Transactional and security requirements • Portable across vendors – part of the JEE specification

  49. Deployment Descriptor jboss.xml • Optional JBoss specific extension • Connect local bean name to global JNDI context

  50. EJB Packaging • myApplication.jar • META-INF • ejb-jar.xml (optional) • jboss.xml (optional) • class files in package subdirectories