1 / 63

Coverage

Coverage. Introduction to Concurrent and Distributed Programming Fork in Unix Threads in Java Network Programming Distributed Programming. Concurrency and Distributed Programming. Introduction.

saniya
Download Presentation

Coverage

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Coverage • Introduction to Concurrent and Distributed Programming • Fork in Unix • Threads in Java • Network Programming • Distributed Programming Concurrency and Distributed Programming

  2. Introduction • Handling processing in parallel is to make execution faster and process multiple tasks simultaneously • Usage of multiple processors to handle processing in parallel is called as multiprocessing • With a single process if we try to handle multiple processing using the interleaving execution of separate tasks, then it is called as multiprogramming • Multiprogramming uses time sharing among processes • Multitasking operating systems could execute many components of a single program (of a single user) concurrently • Each program segment is called as a process or task. Each process has its own thread of control. Thread of control in a process indicates the points in the process that have been reached, as the control flows within the process Concurrency and Distributed Programming

  3. Introduction Executing statements in sequence is done deterministically in sequential systems Deterministic means that multiple execution of a program on the same set of data will provide the same computation Executing statements concurrently or parallel (concurrent systems) could cause non-deterministic nature, where the results might differ between different executions of the same program Java or C or C++ or C#: execution of statements concurrently or parallely can be done using threads (light-weight processes) A program is a heavy-weight process where the whole program has it own memory and other resources allocated In the case of light-weight processes, threads need to share the memory with the program from which it was invoked 3 Concurrency and Distributed Programming

  4. Introduction If various processors share the same memory then the system is called as shared-memory system (also called as multiprocessor system) If they have individual memory of their own and yet work together then they are called as distributed systems (also called as multicomputer system) Types of Parallelism Task Parallelism Perform different tasks concurrently Instruction-level parallelism: More than one machine instruction is executed in parallel Statement-level parallelism: Group of statements are executed in parallel Procedure-level (or unit-level) parallelism: Execute different procedures or subprograms in parallel Program-level parallelism: Whole process is copied and execute as child and parent in parallel, as like fork in Unix. Data Parallelism: Data is divided into smaller sets and worked parallely 4 Concurrency and Distributed Programming

  5. Introduction Issues faced by concurrent programs Deadlock occurs when more than one concurrent process awaits the resource being held exclusively by another process Starvation is possible when a process waits permanently for a blocked resource Modifying a memory location should be done only by a single process at a time. This concept of allowing only one access at a time is called as Mutual exclusion Without mutual exclusion, different processes might access and modify the memory location in an unpredictable way. This situation is called as race condition The concept of any process entering within the critical section is certain to complete, is called as Liveness If access to the critical section by various processes is given in a fair manner, then it is called as Fairness 5 Concurrency and Distributed Programming

  6. Introduction Parallel computing uses shared memory to exchange information between different processors, while distributed computing uses message passing techniques to exchange information between different processors. In distributed computing, each distributed processor can have their separate private memory 6 Concurrency and Distributed Programming

  7. Middleware Programming on heterogeneous systems require different methodologies to be followed To abstract the complex heterogeneous nature from the programmer, a software layer named middleware is used Middleware provides the programmer with the necessary programming interfaces to handle object invocation, transactions processing, sharing of resources, etc With appropriate language independent interfaces, programmers can specify the required implementation structure. With marshalling and unmarshalling, differences in the data formats between different system computer architectures is taken care of Middleware Examples: Sun RPC (Remote Procedure Calls), OMG CORBA (Common Request Broker Architecture), Microsoft D-COM (Distributed Components Object Model),Open Distributed Processing (ODP) - (ITU-T/ISO) – (RM-ODP), Sun Java RMI (Remote Method Invocation) Modern Middleware: Melbourne Gridbus – for Grid computing, ANL Globus – a Grid toolkit, IBM WebSphere, Microsoft .NET, Sun J2EE 7 Concurrency and Distributed Programming

  8. Middleware 8 Concurrency and Distributed Programming

  9. Semaphore Semaphore is used to provide mutual exclusion and synchronization in shared-memory system The region of the program that is permitted to be accessed by only one process at a time is called as critical region Threads share a single address space and thus could access the same data and variables. If two threads access a global state at the same time, then it might modify the global state incorrectly. To prevent this from happening, we need semaphores Binary semaphore based on its value, permits or denies access to the shared resource Only one process can access the resource at a time Presence of one value indicates the critical section is free and thus the process can decrement it and enter the critical section Presence of zero value indicates the critical section is in use Upon exit, the semaphore must be set back to one value 9 Concurrency and Distributed Programming

  10. Semaphore Counting Semaphore More than one thread can enter the critical section at a time If the counter value is zero, threads have to wait before entering into the critical section Accessing the semaphore P and V functions, which are atomic in nature P stands for passaren (means pass in Dutch) or prolagen in Dutch which is formed from two words: proberen (to try) and verlagen (for decrease); V stands for verhogen which means to increase or vrigevan which means to release P (Semaphore s) // Acquire the resource – similar to wait in Java { if s > 0, then s = s -1 else wait;} V (Semaphore s) // Release the resource – similar to notify in Java { s = s + 1;} Init (Semaphore s, Integer v) // Initialize the resource { s = v;} 10 Concurrency and Distributed Programming

  11. Semaphore Any thread that wishes to enter the critical section will do the below: Use P function (wait function) to acquire the critical section. If successful, the critical section is being processed. Upon the completion of the critical section tasks, V function (signal function) should be executed to release the lock Problems with atomic operations: Deadlock: If one process acquires resource A and waits for resource B. Another process acquires resource B and waits for resource A. After acquiring a resource (using wait function), if the release was not done properly using signal function If wait(A) is again followed by wait(A) instead of signal(A), then the process will be blocked by the resource currently on hold by its own. If signal(A) precedes wait(A), then the resource which is not being held is tried to be released 11 Concurrency and Distributed Programming

  12. Semaphores in Unix Semaphore structure has following elements: semval: Semaphore value sempid: Process id of last operation semncnt: Number of processes waiting for semval to become greater than current value semzcnt: Number of processes waiting for semval to become zero semget() function: Used to get the semaphore identifier when the key is provided as a parameter to it nsems argument indicates the number of semaphores Returns an array of semaphore identifiers based on nsems include <sys/sem.h> int semget (key_t key, int nsems, int semflg); semctl() function: Control the semaphore using various commands int semctl (int semid, int semnum, int cmd, ...); 12 Concurrency and Distributed Programming

  13. Semaphores in Unix semctl() function: semnum is index to be used with the semid array returned by the semget() function GETVAL, SETVAL, GETPID, GETNCNT, GETZCNT, GETALL, SETALL, etc are some of the valid commands semop() function: int semop (int semid, struct sembuf *sops, size_t nsops); Perform an array of operations specified by the user on the semaphore The user defined operations are specified in the sembuf structure To indicate how many structures are present in the array, the nsops argument is used. semop() function returns zero on success and -1 on error 13 Concurrency and Distributed Programming

  14. Semaphores in Unix (semaphoreinit.c) #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdio.h> #define KEY (1492) // key required by semaphores void main() { int semaphoreid; // Semaphore Identifier union semun { int val; struct semid_ds *buf; ushort * array; } argument; argument.val = 0; semaphoreid = semget(KEY, 1, 0666 | IPC_CREAT); if(semaphoreid < 0){ fprintf(stderr, "Unable to obtain semaphore.\n"); exit(0); } if( semctl(semaphoreid, 0, SETVAL, argument) < 0) { fprintf( stderr, "Operation not successful.\n"); } else { fprintf(stderr, "Semaphore with %d is initialized.\n", KEY); } } 14 Concurrency and Distributed Programming

  15. Semaphores in Unix (Psemaphore.c) #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define KEY (1492) void main() { int semaphoreid; // semaphore identifier struct sembuf operation[1]; // Semaphore operations array int returnvalue; // Return value of semop() semaphoreid = semget(KEY, 1, 0666); if(semaphoreid < 0) { printf("Psemaphore Program cannot find semaphore.\n"); exit(0); } // we need to read the 0th element of the semaphore array operation[0].sem_num = 0; // the operation we want to perform is subtraction. operation[0].sem_op = -1; // set the flag to wait for the operation. operation[0].sem_flg = 0; returnvalue = semop(semaphoreid, operation, 1); if(returnvalue == 0) { printf("P-operation handled.\n"); } else { printf("P-operation was not successful.\n"); } } 15 Concurrency and Distributed Programming

  16. Semaphores in Unix (Vsemaphore.c) #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define KEY (1492) void main() { int semaphoreid; // semaphore identifier struct sembuf operation[1]; // semaphore operations array int returnvalue; // return from semop() function semaphoreid = semget(KEY, 1, 0666); if(semaphoreid < 0) { fprintf(stderr, "Vsemaphore cannot find semaphore.\n"); exit(0); } // we need to read the 0th element of the semaphore array operation[0].sem_num = 0; // the operation to perform is adding 1 to semaphore value operation[0].sem_op = 1; // set the flag to wait for the operation. operation[0].sem_flg = 0; returnvalue = semop(semaphoreid, operation, 1); if(returnvalue == 0) { printf("V-operation handled.\n"); } else { printf("V-operation can not be performed.\n"); } } 16 Concurrency and Distributed Programming

  17. Introduction Monitors Used to indicate mutual exclusion and synchronization mechanisms of semaphores Monitor is an abstract data type by itself because it includes the shared data and the necessary operations Monitor by itself does not provide any conditional checking to make a process wait Monitor in Java: Can be handled using synchronized reserved word Concurrency Constructs Various concurrency constructs exist: (fork and join), (cobegin and coend) or (parbegin and parend) Precedence Graph Precedence Graph is a directed, acyclic graph that could be used to represent the flow of execution of a process Nodes represent statements and arcs represent executions Executing statements (S1;S2; …) in sequence Acyclic in nature, loops are not allowed 17 Concurrency and Distributed Programming

  18. Introduction Petri Nets (Uses Places, Tokens, Transition, Arcs and Marks) Places (represented as circles) are used to represent pre-conditions or program counter's values or state of the system Tokens (represented with shaded circle) are present in places Transition is used to indicate any statement or program execution Marks are used to indicate the flow of execution with the help of arcs 18 Concurrency and Distributed Programming

  19. Introduction Fork and Join Fork(label); is used to create a new thread. Thus, there will be two threads running concurrently The newly created second thread should execute the statement that is labeled as the label mentioned in the Fork statement The statement Join(count); is used to decrement the value of the count and if the resultant value of count is positive, then the thread is terminated 19 Concurrency and Distributed Programming

  20. Introduction CoBegin and CoEnd Also called as ParBegin and ParEnd cobegin S1; S2; … Sn; coend; When cobegin is executed, each statement that follow the cobegin statement is executed individually in separate threads These threads are executed concurrently and the processing will stop when coend is executed 20 Concurrency and Distributed Programming

  21. Introduction forall Used to accomplish data parallelism by applying the same set of instructions on different set of data forall (parameters) statements Fork in Unix A fork call creates a child process which has the exact copy of the calling procedures if (fork() == 0 ) { /* Child Part */ } else { /* Parent Part */ } Once the child completes its execution, parent part will be executed Threads in Java Processes are run from the run method To start the run method, start method needs to be called run method cannot have any specific parameters to be passed or anything to be returned Threads are built in the java.lang package The reserved word synchronized is used to provide mutual exclusion among threads 21 Concurrency and Distributed Programming

  22. Fork example (Parent prints ‘a’; child prints ‘b’) #include <stdio.h> int main() { int fork_return; int count = 0; fork_return = fork(); if( fork_return < 0) { printf("Unable to create child process, exiting.\n"); exit(-1); } if( fork_return > 0) { printf("Created child process %d.\n", fork_return); while( count++ < 800) { putchar('a'); if(count % 80 == 0){ putchar('\n'); sleep(2); } } } else { while(count++ < 800) { putchar('b'); if(count % 80 == 0){ putchar('\n'); sleep(2); } } } } 22 Concurrency and Distributed Programming

  23. Threads in Java Start the threads using: test.start(); The join method is used to make one process wait for another The interrupt method is used to indicate the threaded process that another process needs something from him interrrupt will not block the process but will set an internal flag in the threaded object Any process that is currently sleeping or waiting will not check the interrupt flag. To handle this, interrupt method also throws an exception InterruptedException that awakens the sleeping or waiting thread 23 Concurrency and Distributed Programming

  24. Threads in Java Threads can be blocked using sleep method The reserved word synchronized is used to prevent multiple processes acting on a single resource at a time To indicate the waiting processes that a lock is released, a notify() or notifyAll() method could be used Threads in Java are assigned a default priority; called as NORM_PRIORITY of 5. The maximum (MAX_PRIORITY) and minimum (MIN_PRIORITY) priority allowed is 10 and 1 respectively setPriority method could be used to assign priority to the thread getPriority method could be used to read the priority assigned to the thread 24 Concurrency and Distributed Programming

  25. Network Programming Sockets act as an interface for programming on the transport layer of networks Socket programming can be done in Java or C or C++ or C# A socket is made up of IP address and a port number Server application is bound to an IP and port number and awaits connection from the client. Client connects to the server with the server’s IP and port number As an example: Web server runs on a well known port number 80 (HTTP port) In http://www.ubd.edu.bn/, http is the protocol, www is the web server’s name, ubd.edu.bn is the domain name Answering multiple clients at a time is possible because after initial connection from the client, the server selects a random port number (Ephemeral port) and communicates to the client from that port number and thus keeping the well known port number open for other clients to connect. 25 Concurrency and Distributed Programming

  26. Network Programming Socket programming can be done for both Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) TCP Sockets in Java java.net package provides Socket and ServerSocket classes Server program Create the Server Socket: ServerSocket server = new ServerSocket(Port); Wait for Clients to connect: Socket client = server.accept(); Make Output stream: OutputStream output = client.getOutputStream(); DataOutputStream doutput = new DataOutputStream(output); Sending Data: doutput.writeUTF("Testing from Server\n"); Close the streams and socket: doutput.close(); output.close(); client.close(); Client program Create the Client Socket: Socket client = new Socket(ServerIP, ServerPort); Make Input stream: InputStream input = client.getInputStream(); DataInputStream dinput = new DataInputStream(input); Receiving Data: String ReceivedData = new String(dinput.readUTF()); Close the streams and socket: input.close(); dinput.close(); client.close(); 26 Concurrency and Distributed Programming

  27. Network Programming TCP Sockets in Java Client program Create the Client Socket: Socket client = new Socket(ServerIP, ServerPort); Make Input stream: InputStream input = client.getInputStream(); DataInputStream dinput = new DataInputStream(input); Receiving Data: String ReceivedData = new String(dinput.readUTF()); Close the streams and socket: input.close(); dinput.close(); client.close(); UDP Sockets in Java Uses DatagramSocket for the sending and receiving program There is no specific server program Import: import java.net.*; import java.io.*; Create a Datagram Socket: DatagramSocket dsocket = new DatagramSocket(PORT); 27 Concurrency and Distributed Programming

  28. Network Programming UDP Sockets in Java Create a buffer to receive data: byte[] buffer = new byte[1000]; Create the datagram packet: DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); Receive the data: dsocket.receive(receivedPacket); Print the Result: System.out.println("Reply: " + new String(receivedPacket.getData())); Sending of the packet (Create and send): InetAddress hostaddr = InetAddress.getByName("127.0.0.1"); int ServerPort = 1234; DatagramPacket sendPacket = new DatagramPacket(receivedData.getData(), receivedData.getLength(), hostaddr, ServerPort); dsocket.send(sendPacket); Close the socket: dsocket.close(); 28 Concurrency and Distributed Programming

  29. Network Programming If we need to send objects between clients and server, then the objects need to be serialized. To serialize the object, we need to implement the java.io.Serializable interface, which has no methods Serialize the given class, whose instance is the object that ought to be transferred between the client and server If a specific variable ought not to be serialized, then use the reserved word transient to it. import java.io.*; public class sendObject implements Serializable { private transient String password; // not serialized. … } Creating the stream to read and write objects: // create server sockets ServerSocket server = new ServerSocket(Port); 29 Concurrency and Distributed Programming

  30. Network Programming // accept the client connections Socket client = server.accept(); // create object input stream InputStream input = client.getInputStream(); ObjectInput oinput = new ObjectInputStream(input); // create object output stream OutputStream output = client.getOutputStream(); ObjectOutput ooutput = new ObjectOutputStream(output); // reading object is handled using readObject method. sendObject x = (sendObject) oinput.readObject(); // writing object is handled using writeObject method followed by flush. ooutput.writeObject(x); ooutput.flush(); Close the stream and sockets: oinput.close(); ooutput.close(); 30 Concurrency and Distributed Programming

  31. Network Programming Securely Transferring Objects using Sockets in Java If we want to transfer the object securely, then we need to use public key and digital signature Generate public and private keys: Using Digital Signature Algorithm (DSA) with key length of 512 bits import java.security.*; KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA"); keygen.initialize(512); // instead of 512, we can use 1024 bits key length as below. // keygen.initialize(1024, new SecureRandom()); KeyPair keypair = keygen.generateKeyPair(); With the public and private key, the digital signature could be produced. Signature sign = Signature.getInstance("SHA/DSA"); // Get the Public key from the key pair PublicKey pub = keypair.getPublic(); // Get the Private key from the key pair PrivateKey priv = keypair.getPrivate(); 31 Concurrency and Distributed Programming

  32. Network Programming With the public and private key, the digital signature could be produced. sign.initSign(priv); // obtain the byte array and sign it. byte data[] = … ; sign.update(data); With the signature, create the object and send the data out using writeObject method. Note that the object that we transfer must contain the byte array, signature and public key. After receiving the object (using readObject method), we need to verify the signature. Signature sign = Signature.getInstance("SHA/DSA"); // Initialize this signature using the public key received from the object. sign.initVerify(object.publickey); // Using the byte array update the signature produced here. sign.update(object.bytearray); 32 Concurrency and Distributed Programming

  33. Network Programming After receiving the object (using readObject method), we need to verify the signature. // check whether the received signature is valid or not. // If true, we have received the data as it is. // Otherwise, the data has been changed on the fly. // sign is the local signature and object.sign is the received signature. boolean valid = sign.verify(object.sign); Java Secure Socket Extension (JSSE): JSSE is part of the Java 2 Platform Standard Edition (J2SE) package Using JSSE, we could develop secure Internet applications that use Secure Socket Layer (SSL) SSL supports encryption, source authentication and data integrity Use javax.net and javax.net.ssl packages instead of java.net and java.security We have SSLServerSocket and SSLSocket as a replacement for ServerSocket and Socket classes. SSLServerSocketFactory and SSLSocketFactory are classes that provide the object factory for creating secure server and client sockets respectively 33 Concurrency and Distributed Programming

  34. Network Programming Create the key store using keytool command Three main options of keytool: genkey, export and import. Generate the keys using genkey option. Generate the keys. keytool –genkeys –keystore sslserverkeys –keyalg rsa –alias co4307ssl Export the generated key into a certificate form. Convert the keys into a certificate file named sslserver.cert keytool –export –keystore sslserverkeys –alias co4307ssl –file sslserver.cert Copy the certificate from the server to the client machine. From this certificate, the appropriate keys have to be imported. keytool –import –keystore sslkeys –alias co4307ssl –file sslserver.cert 34 Concurrency and Distributed Programming

  35. Network Programming Creating the Key Store. import javax.net.ssl.*; import java.security.*; // name of the key store as used in keytool String keystore = "sslserverkeys"; // Provide the key password and key store password in character array. // These values can be passed as command line arguments also. // These passwords (need not be the same) were used in the process of keys generation in keytool. char keypassword[] = "co4307ssl".toCharArray(); // key password char keystorepass[] = "co4307ssl".toCharArray(); // key store password // JKS is the Java Key Store KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore), keystorepass); Key Manager (X.509 key manager) is used to manage the key store. KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, keypassword); 35 Concurrency and Distributed Programming

  36. Network Programming Create the SSL socket. SSLContext sslcontext = SSLContext.getInstance("SSLv3"); sslcontext.init(kmf.getKeyManagers(), null, null); SSLServerSocketFactory ssf = sslcontext.getServerSocketFactory(); SSLServerSocket server = (SSLServerSocket) ssf.createServerSocket(PORT); SSLSocket clientSocket = (SSLSocket) server.accept(); Use the data input and output stream to send and receive data Creating client programs using JSSE Get the SSLSocket factory and create the SSLSocket. import javax.net.ssl.*; import java.net.*; int ServerPort = 1234; String ServerName = "127.0.0.1"; SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault(); SSLSocket client = (SSLSocket)factory.createSocket(ServerName, ServerPort); 36 Concurrency and Distributed Programming

  37. Network Programming Creating client programs using JSSE Create data input and output stream to send and receive data. While running the client program, provide the key store information at the command line using: java –Djavax.net.ssl.trustStore=sslkeys Client … Proxy information can also be provided at the command line using: java –Dhttp.proxyHost=proxy.test.com –Dhttp.proxyPort=8080 … Proxy information with username and password: java –Dhttp.proxyHost=username:password@proxy.test.com –Dhttp.proxyPort=8080 … Proxy information with bypassing proxy for certain hosts: java –Dhttp.proxyHost=username:password@proxy.test.com –Dhttp.proxyPort=8080 -Dhttp.nonProxyHosts="localhost|www.test.com" … 37 Concurrency and Distributed Programming

  38. Network Programming Multicast Sockets in Java One sender and many receivers Multicast sender: Create the multicast socket using a multicast group address and port number: import java.net.*; import java.io.*; int port = 1234; // choose a Class D IP address String groupaddress = "239.1.2.3"; InetAddress groupadd = InetAddress.getByName(groupaddress); MulticastSocket msocket = new MulticastSocket(port); Create the Datagram Packet: byte[] buffer = new byte[1000]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length, groupadd, port); Set the time to live for the packet: msocket.setTimeToLive(32); Send the packets: msocket.send(packet); Close the socket: msocket.close(); 38 Concurrency and Distributed Programming

  39. Network Programming Multicast Sockets in Java Multicast receiver: Create the multicast socket using a multicast group address and port number: import java.net.*; import java.io.*; int port = 1234; // same as the sender String groupaddress = "239.1.2.3"; // same as the sender InetAddress groupadd = InetAddress.getByName(groupaddress); MulticastSocket msocket = new MulticastSocket(port); In order to receive multicast packets, the receiver must join to the multicast group. msocket.joinGroup(groupadd); Create the Datagram Packet to receive the data: byte[] buffer = new byte[1000]; DatagramPacket receivepacket = new DatagramPacket(buffer, buffer.length); Receive the packets: msocket.receive(receivepacket); Leave the group and close the connection. msocket.leaveGroup(groupadd); msocket.close(); 39 Concurrency and Distributed Programming

  40. Distributed Programming Java Remote Method Invocation (Java RMI) Enable programmers to develop Java based applications that could invoke methods of remote Java objects present in different hosts The process of marshalling and unmarshalling of data is handled using serialization 40 Concurrency and Distributed Programming

  41. Distributed Programming Java Remote Method Invocation (Java RMI) Server side components Servant: Actual instance of the class Skeleton: Interface at server; unmarshals arguments and invokes servant; marshals result and returns them Dispatcher: one dispatcher per class representing a remote object; Used to select the appropriate skeleton Client side components Proxy: Used to invoke appropriate remote object Java RMI Server Requires implementation and interface The interface program extends Remote and throws RemoteException The implementation program extends UnicastRemoteObject and implements the interface Rmiregistry is used by the server to post his service so that client could search for a specific service With interface and implementation, the following has to be done: Compile both the interface and the implementation programs. javac HelloWorld.java javac HelloWorldImpl.java Generate the stubs using rmic command with the implementation program. rmic HelloWorldImpl Start the rmiregistry as below: In Linux: With default port number 1099: rmiregistry & With a port number (10000, in this case): rmiregistry 10000 & In Windows: start rmiregistry Run the server program as: java HelloWorldImpl 41 Concurrency and Distributed Programming

  42. Distributed Programming Java Remote Method Invocation (Java RMI) Java RMI Server With interface and implementation, the following has to be done: Compile both the interface and the implementation programs. javac HelloWorld.java javac HelloWorldImpl.java Generate the stubs using rmic command with the implementation program. rmic HelloWorldImpl Start the rmiregistry as below: In Linux with default port number 1099: rmiregistry & In Linux with a port number (10000, in this case): rmiregistry 10000 & In Windows: start rmiregistry Run the server program as: java HelloWorldImpl 42 Concurrency and Distributed Programming

  43. Distributed Programming Java Remote Method Invocation (Java RMI) Java RMI Client Requires the interface and stub program from the server After coding the client program, the following has to be done: Compile both the client program. We need the interface class for compiling. java RMIClient.java Copy the stub program from the server to run the client program. java RMIClient Instead of copying the stub, stub downloading can be done as: Add the following lines to both the client and the server implementation programs. import java.rmi.*; System.setSecurityManager(new RMISecurityManager()); 43 Concurrency and Distributed Programming

  44. Distributed Programming Java Remote Method Invocation (Java RMI) Java RMI Client Instead of copying the stub, stub downloading can be done as: Write a security policy file (let's name it as policy.java), which should be present at the client and server machines. grant { permission java.security.AllPermission "", ""; }; Run the server program as: java –Djava.security.policy=java.policy HelloWorldImpl Run the client program as: Note that the stub program (HelloWorldImpl_Stub.class) is present in the web server which is running on the localhost (127.0.0.1) at port number 8080. java –Djava.rmi.server.codebase=http://127.0.0.1:8080/ -Djava.security.policy=java.policy RMIClient 44 Concurrency and Distributed Programming

  45. Distributed Programming Java Remote Method Invocation (Java RMI) Java RMI Client Better security policy file can be: grant { // permits socket access to all common TCP ports, including the default // RMI registry port (1099) – need for both the client and the server. permission java.net.SocketPermission "*:1024-65535", "connect,accept,resolve"; // permits socket access to port 80, the default HTTP port – needed // by client to contact an HTTP server for stub downloading permission java.net.SocketPermission "*:80", "connect"; }; 45 Concurrency and Distributed Programming

  46. Distributed Programming Jini and JavaSpaces Jini is not an acronym Jini is a set of APIs that help programmers to write and deploy distributed systems Jini provides the programmer with options to register and search for a service In order to search or find a service, there should be some registry where the client could search for the service. This registry is provided in the form of Jini Lookup Server (LUS) Jini uses RMI for its remote communication Jini Protocols: Discovery and Join Protocol Discovery Protocol:Discovery protocol is used by various Jini clients to locate the Jini Lookup Server This Discovery service could be handled using Unicast Discovery Protocol or Mutlicast Request Protocol or Multicast Announcement Protocol Join Protocol:After discovering or locating the Lookup Server, the client needs to register with the Lookup Server. This process of registering is done using Join Protocol 46 Concurrency and Distributed Programming

  47. Distributed Programming Jini Operation Jini service has to locate the LUS (using Discovery Protocol) and register its service with LUS Jini clients also have to locate LUS and then search for the required service. Once the client knows the service, it could talk to the service directly Jini Working After installation, Jini could be started using the Launch-All file present in the installVerify folder of the jini installation directory. Jini runs six services Lookup Service (Service Registrar): uses reggie file. Persistence Service (JavaSpaces): uses outrigger file. Transaction Service: uses mahalo file. Lookup Discovery Service: uses fiddler file. Lease Renewal Service: uses norm file. Event Mailbox Service: uses mercury file Jini Programs: Server program need interface and implementation. Client needs interface. 47 Concurrency and Distributed Programming

  48. Distributed Programming Jini Programs Compile the Interface program: javac MyServerInterface.java Compile the Implementation and client programs: Assume that the jini is installed at C:\jini and /home/student/jini folders on Windows and Linux respectively Note the use of semi-colon in Windows and colon in Linux commands. On Windows: javac –classpath C:\jini\classes;. MyService.java javac –classpath C:\jini\classes;. MyClient.java On Linux: javac –classpath /home/student/jini/classes:. MyService.java javac –classpath /home/student/jini/classes:. MyClient.java Generate the stub using: rmic MyService 48 Concurrency and Distributed Programming

  49. Distributed Programming Jini Programs Run the client and server programs: On Windows: java –classpath C:\jini\classes;. MyService java –classpath C:\jini\classes;. MyClient On Linux: java –classpath /home/student/jini/classes:. MyService java –classpath /home/student/jini/classes:. MyClient As an alternative the classpath could be changed to /home/student/jini/lib/jini-ext.jar:/home/student/jini/lib/reggie.jar You could follow the process of using security policy file and stub downloading as discussed before Jini installation includes a service called JavaSpaces JavaSpaces use shared areas or spaces for communication, instead of message passing 49 Concurrency and Distributed Programming

  50. Distributed Programming JavaSpaces Operations that could be handled using JavaSpaces are read, take, write and notify The method write() is used to write new objects to the space The method take() is used to retrieve objects from the space The method read() is used to make a copy of the objects in the space The method notify() is used to notify when an entry that matches the given template is written to the space Objects are passive data stores and thus the objects can not be directly modified. They must be explicitly removed and then updated and reinserted into the space Compilation is similar to that of Jini Execution is like: For Linux: java –classpath /home/student/jini/lib/jini-ext.jar:/home/student/jini/lib/reggie.jar:/home/student/jini/lib/outrigger.jar:. filename For Windows: java –classpath C:\jini\lib\jini-ext.jar;C:\jini\lib\reggie.jar;C:\jini\lib\outrigger.jar;. filename 50 Concurrency and Distributed Programming

More Related