BE - IT - LP-V Lab Manual - 17!04!23
BE - IT - LP-V Lab Manual - 17!04!23
FINAL YEAR
INFORMATION TECHNOLOGY
(2019 COURSE)
LABORATORY MANUAL
FOR
LABORATORY PRACTICE - V
SEMESTER - VIII
[Subject code: 414454]
[Prepared By]
Mr. L.V.Patil Mrs. P. S. Pise
Page 1 of 60
VISION
MISSION
VISION
MISSION
Problem Statement:
Implement multi-threaded client/server Process communication using RMI.
Tools / Environment:
Java Programming Environment, jdk 1.8, rmiregistry
Theory:
RMI provides communication between java applications that are deployed on different servers and
connected remotely using objects called stub and skeleton. This communication architecturemakes
a distributed application seem like a group of objects communicating across a remote connection.
These objects are encapsulated by exposing an interface, which helps access the private state and
behavior of an object through its methods.
The following diagram shows how RMI happens between the RMI client and RMI server with
thehelp of the RMI registry:
Page 5 of 60
RMI REGISTRY is a remote object registry, a Bootstrap naming service, that is used by RMI
SERVER on the same host to bind remote objects to names. Clients on local and remote hosts then
look up the remote objects and make remote method invocations.
If any object invokes a method on the stub object, the stub establishes RMI by following these
steps:
1. It initiates a connection to the remote machine JVM.
2. It marshals (write and transmit) the parameters passed to it via the remote JVM.
3. It waits for a response from the remote object and unmarshals (read) the returned value
or exception, then it responds to the caller with that value or exception.
Skeleton: This is an object that behaves like a gateway on the server side. It acts as a remote object
with which the client objects interact through the stub. This means that any requests coming from
the remote client are routed through it. If the skeleton receives a request, itestablishes RMI through
these steps:
1. It reads the parameter sent to the remote method.
2. It invokes the actual remote object method.
3. It marshals (writes and transmits) the result back to the caller (stub).
The following diagram demonstrates RMI communication with stub and skeleton involved:
Page 6 of 60
Designing the solution:
The essential steps that need to be followed to develop a distributed application with RMI are as
follows:
1. Design and implement a component that should not only be involved in the distributed
application, but also the local components.
2. Ensure that the components that participate in the RMI calls are accessible across networks.
3. Establish a network connection between applications that need to interact using the RMI.
Remote interface definition: The purpose of defining a remote interface is to declare the methods
that should be available for invocation by a remote client.
Programming the interface instead of programming the component implementation is an essential
design principle adopted by all modern Java frameworks, including Spring. In the same pattern,
the definition of a remote interface takes importance in RMI design as well.
1 Remote object implementation: Java allows a class to implement more than one interface ata
time. This helps remote objects implement one or more remote interfaces. The remote object class
may have to implement other local interfaces and methods that it is responsible for. Avoid adding
complexity to this scenario, in terms of how the arguments or return parameter values of such
component methods should be written.
2 Remote client implementation: Client objects that interact with remote server objects can be
written once the remote interfaces are carefully defined even after the remote objects are deployed.
Let's design a project that can sit on a server. After that different client projects interact with this
project to pass the parameters and get the computation on the remote object execute and return the
result to the client components.
The server receives a request from a client, processes it, and returns a result. In this example, the
request specifies two numbers. The server adds these together and returns the sum.
This application uses four source files. The first file, AddServerIntf.java, defines the remote
interface that is provided by the server. It contains one method that accepts two doublearguments
and returns their sum. All remote interfaces must extend the Remoteinterface, whichis part of
java.rmi. Remote defines no members. Its purpose is simply to indicate that an interface uses
remote methods. All remote methods can throw a RemoteException.
Page 7 of 60
The second source file, AddServerImpl.java, implements the remote interface. The
implementation of the add() method is straightforward. All remote objects must extend
UnicastRemoteObject, which provides functionality that is needed to make objects available from
remote machines.
The third source file, AddServer.java, contains the main program for the server machine. Its
primary function is to update the RMI registry on that machine. This is done by using the rebind()
method of the Namingclass (found in java.rmi). That method associates a namewith an object
reference. The first argument to the rebind() method is a string that names the server as
“AddServer”. Its second argument is a reference to an instance of AddServerImpl.
The fourth source file, AddClient.java, implements the client side of this distributed application.
AddClient.java requires three command-line arguments. The first is the IP address or name of the
server machine. The second and third arguments are the two numbers thatare to be summed.
The application begins by forming a string that follows the URL syntax. This URL uses the rmi
protocol. The string includes the IP address or name of the server and the string “AddServer”. The
program then invokes the lookup( ) method of the Naming class. This method accepts one
argument, the rmi URL, and returns a reference to an object of type AddServerIntf. All remote
method invocations can then be directed to this object.
The program continues by displaying its arguments and then invokes the remote add()method.The
sum is returned from this method and is then printed.
Use javac to compile the four source files that are created.
2. Generate a Stub
Before using client and server, the necessary stub must be generated. In the context of RMI, a
stub is a Java object that resides on the client machine. Its function is to present the same
interfaces as the remote server. Remote method calls initiated by the client are actually directed
to the stub. The stub works with the other parts of the RMI system to formulate a request that is
sent to the remote machine.
All of this information must be sent to the remote machine. That is, an object passed as an argument
to a remote method call must be serialized and sent to the remote machine. If a response must be
returned to the client, the process works in reverse. The serialization and deserialization facilities
are also used if objects are returned to a client.
To generate a stub the command is RMIcompiler is invoked as follows:
rmic AddServerImpl.
This command generates the file AddServerImpl_Stub.class.
Java provides a program called rmiregistry, which executes on the server machine. It mapsnames
to object references. Start the RMI Registry from the command line, as shown here:
start rmiregistry
The server code is started from the command line, as shown here:
java AddServer
The AddServer code instantiates AddServerImpl and registers that object with the name
“AddServer”.
The AddClient software requires three arguments: the name or IP address of the server machine
and the two numbers that are to be summed together. You may invoke it from the command line
by using one of the two formats shown here:
Page 9 of 60
Writing the source code:
Page 10 of 60
Compilation and Executing the solution:
The steps for compilation and execution are captured in a snapshots given:
Page 11 of 60
Conclusion:
Remote Method Invocation (RMI) allows you to build Java applications that are distributed among
several machines. Remote Method Invocation (RMI) allows a Java object that executeson one
machine to invoke a method of a Java object that executes on another machine. This is an important
feature, because it allows you to build distributed applications.
Page 12 of 60
ASSIGNMENT NO. 2
Problem Statement:
To develop any distributed application using CORBA to demonstrate object brokering. (Calculator or
String operations).
Tools / Environment:
Theory:
CORBA is an acronym for Common Object Request Broker Architecture. It is an open source,
vendor-independent architecture and infrastructure developed by the Object Management Group
(OMG) to integrate enterprise applications across a distributed network. CORBA specifications
provide guidelines for such integration applications, based on the way they want to interact,
irrespective of the technology; hence, all kinds of technologies can implement these standards using
their own technical implementations.
When two applications/systems in a distributed environment interact with each other, there are quite
a few unknowns between those applications/systems, including the technology they are developed in
(such as Java/ PHP/ .NET), the base operating system they are running on (such as Windows/Linux),
or system configuration (such as memory allocation). They communicate mostly with the help of
each other's network address or through a naming service. Due to this, these applications end up
with quite a few issues in integration, including content (message) mapping mismatches.
An application developed based on CORBA standards with standard Internet Inter-ORB Protocol
(IIOP), irrespective of the vendor that develops it, should be able to smoothly integrateand operate
with another application developed based on CORBA standards through the same or different
vendor.
Except legacy applications, most of the applications follow common standards when it comes to
object modeling, for example. All applications related to, say, "HR&Benefits" maintain an object
model with details of the organization, employees with demographic information, benefits,payroll,
and deductions. They are only different in the way they handle the details, based on the country and
region they are operating for. For each object type, similar to the HR&Benefits systems, we can
define an interface using the Interface Definition Language (OMG IDL).
The contract between these applications is defined in terms of an interface for the server objects that
the clients can call. This IDL interface is used by each client to indicate when they should call any
particular method to marshal (read and send the arguments).
The target object is going to use the same interface definition when it receives the request from the
client to unmarshal (read the arguments) in order to execute the method that was requested bythe
client operation. Again, during response handling, the interface definition is helpful tomarshal (send
from the server) and unmarshal (receive and read the response) arguments on the client side once
Page 13 of 60
received.
The IDL interface is a design concept that works with multiple programming languages including
C, C++, Java, Ruby, Python, and IDLscript. This is close to writing a program to an interface, a
concept we have been discussing that most recent programming languages and frameworks, such as
Spring. The interface has to be defined clearly for each object. The systems encapsulate the actual
implementation along with their respective data handling and processing, and only the methods are
available to the rest of the world through the interface. Hence, the clients are forced to develop their
invocation logic for the IDL interface exposed by the application they want to connect to with the
method parameters (input and output) advised by theinterface operation.
The following diagram shows a single-process ORB CORBA architecture with the IDL configured
as client stubs with object skeletons, The objects are written (on the right) and a clientfor it (on the
left), as represented in the diagram. The client and server use stubs and skeletons as proxies,
respectively. The IDL interface follows a strict definition, and even though the client and server are
implemented in different technologies, they should integrate smoothly with the interface definition
strictly implemented.
In CORBA, each object instance acquires an object reference for itself with the electronic token
identifier. Client invocations are going to use these object references that have the ability to figure
out which ORB instance they are supposed to interact with. The stub and skeletonrepresent the client
and server, respectively, to their counterparts. They help establish thiscommunication through ORB
and pass the arguments to the right method and its instance during the invocation.
Page 14 of 60
Inter-ORB communication
The following diagram shows how remote invocation works for inter-ORB communication. It shows
that the clients that interacted have created IDL Stub and IDL Skeleton based on Object Request
Broker and communicated through IIOP Protocol.
To invoke the remote object instance, the client can get its object reference using a naming service.
Replacing the object reference with the remote object reference, the client can make the invocation
of the remote method with the same syntax as the local object method invocation. ORB keeps the
responsibility of recognizing the remote object reference based on the client object invocation
through a naming service and routes it accordingly.
CORBA standards provide the proven, interoperable infrastructure to the Java platform. IIOP
(Internet Inter-ORB Protocol) manages the communication between the object components that
power the system. The Java platform provides a portable object infrastructure that works on
every major operating system. CORBA provides the network transparency, Java provides the
implementation transparency. An Object Request Broker (ORB) is part of the Java Platform. The
ORB is a runtime component that can be used for distributed computing using IIOP
communication. Java IDL is a Java API for interoperability and integration with CORBA.Java
IDL included both a Java-based ORB, which supported IIOP, and the IDL-to-Java
Page 15 of 60
compiler, for generating client-side stubs and server-side code skeletons. J2SE v.1.4 includes an
Object Request Broker Daemon (ORBD), which is used to enable clients to transparently locate
and invoke persistent objects on servers in the CORBA environment.
When using the IDL programming model, the interface is everything! It defines the points of entry
that can be called from a remote process, such as the types of arguments the called procedure will
accept, or the value/output parameter of information returned. Using IDL, the programmer can make
the entry points and data types that pass between communicating processes act like a standard
language.
CORBA is a language-neutral system in which the argument values or return values are limitedto
what can be represented in the involved implementation languages. In CORBA, object orientation is
limited only to objects that can be passed by reference (the object code itself cannotbe passed from
machine-to-machine) or are predefined in the overall framework. Passed and returned types must be
those declared in the interface.
With RMI, the interface and the implementation language are described in the same language, so you
don't have to worry about mapping from one to the other. Language-level objects (the code itself)
can be passed from one process to the next. Values can be returned by their actual type,not the
declared type. Or, you can compile the interfaces to generate IIOP stubs and skeletons which allow
your objects to be accessible from other CORBA-compliant languages.
Java IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java
platform, providing standards-based interoperability and connectivity. Runtime components include
a Java ORB for distributed computing using IIOP communication.
To use the IDL programming model, define remote interfaces using OMG Interface Definition
Language (IDL), then compile the interfaces using idlj compiler. When you run the
idlj compiler over your interface definition file, it generates the Java version of theinterface, as
well as the class code files for the stubs and skeletons that enable applications to hook into the ORB.
Portable Object Adapter (POA) : An object adapter is the mechanism that connects a request using
an object reference with the proper code to service that request. The Portable Object Adapter, or
POA, is a particular type of object adapter that is defined by the CORBA specification. The POA is
designed to meet the following goals:
Allow programmers to construct object implementations that are portable between different
ORB products.
Provide support for objects with persistent identities.
Page 16 of 60
Designing the solution:
Here the design of how to create a complete CORBA (Common Object Request Broker Architecture)
application using IDL (Interface Definition Language) to define interfaces and Java IDL compiler
to generate stubs and skeletons. You can also create CORBA application by defining the interfaces
in the Java programming language.
The server-side implementation generated by the idlj compiler is the Portable Servant Inheritance
Model, also known as the POA(Portable Object Adapter) model. This document presents a sample
application created using the default behavior of the idlj compiler, which uses a POA server-side
model.
In order to distribute a Java object over the network using CORBA, one has to define it's
own CORBA-enabled interface and it implementation. This involves doing the following:
Writing an interface in the CORBA Interface Definition Language
Generating a Java base interface, plus a Java stub and skeleton class, using an IDL-to-Java
compiler
Writing a server-side implementation of the Java interface in Java
Modules
Modules are declared in IDL using the module keyword, followed by a name for the module and an
opening brace that starts the module scope. Everything defined within the scope of this module
(interfaces, constants, other modules) falls within the module and is referenced in other IDL modules
using the syntax modulename::x. e.g.
// IDL module
jen {
module corba {
interface NeatExample ...
};
};
Interfaces
The declaration of an interface includes an interface header and an interface body. The header
specifies the name of the interface and the interfaces it inherits from (if any). Here is an IDL interface
header:
This header starts the declaration of an interface called PrintServer that inherits all the methods and
data members from the Serverinterface.
Page 17 of 60
Data members and methods
The interface body declares all the data members (or attributes) and methods of an interface.
Data members are declared using the attribute keyword. At a minimum, the declaration includes a
name and a type.
The method can be declared by specifying its name, return type, and parameters, at a minimum.
This declares a method called parseString() that accepts a single string argument and returns a string
value.
Now let's tie all these basic elements together. Here's a complete IDL example thatdeclares a
module within another module, which itself contains several interfaces:
module OS {
module services { interface
Server {
readonly attribute string serverName;boolean init(in
string sName);
};
interface Printable {
boolean print(in string header);
};
The first interface, Server, has a single read-only string attribute and an init() method that accepts a
string and returns a boolean. The Printable interface has a single print()method that accepts a string
header. Finally, the PrintServerinterface extends the Server interface and adds a printThis() method
that accepts a Printable object and returns a boolean. In all cases, we've declared the method
arguments as input-only (i.e., pass-by-value), using the inkeyword.
Page 18 of 60
2. Turning IDL Into Java
Once the remote interfaces in IDL are described, you need to generate Java classes that actas
a starting point for implementing those remote interfaces in Java using an IDL-to-Java
compiler. Every standard IDL-to-Java compiler generates the following 3 Java classes from an IDL
interface:
A Java interface with the same name as the IDL interface. This can act as the basis for a Java
implementation of the interface (but you have to write it, since IDL doesn't provide any details
about method implementations).
A helper class whose name is the name of the IDL interface with "Helper" appended to it (e.g.,
ServerHelper). The primary purpose of this class is to provide a static narrow()
method that can safely cast CORBA Object references to the Java interface type. The
helper class also provides other useful static methods, such as read() and write()
methods that allow you to read and write an object of the corresponding type using I/O
streams.
A holder class whose name is the name of the IDL interface with "Holder" appended to it (e.g.,
ServerHolder). This class is used when objects with this interface are usedas out or
inout arguments in remote CORBA methods. Instead of being passed directly into the remote
method, the object is wrapped with its holder before being passed.
When a remote method has parameters that are declared as out or inout, the method has to be
ableto update the argument it is passed and return the updated value. The only way to
guarantee this, even for primitive Java data types, is to force outand inoutarguments to be
wrappedin Java holder classes, which are filled with the output value of the argument when
the method returns.
So, in addition to generating a Java mapping of the IDL interface and some helper classes for the
Java interface, the idltoj compiler also creates subclasses that act as an interface between a CORBA
client and the ORB and between the server-side implementation and the ORB.
This creates the five Java classes: a Java version of the interface, a helper class, a holder class,
a client stub, and a server skeleton.
Page 19 of 60
3. Writing the Implementation
The IDL interface is written and generated the Java interface and support classes for it, including
the client stub and the server skeleton. Now, concrete server-side implementations of all of the
methods on the interface needs to be created.
Page 20 of 60
3. Implementing the Client Application (HelloClient.java)
Page 21 of 60
Page 22 of 60
Building and Executing the solution:
The Hello World program lets you learn and experiment with all the tasks required to develop almost
any CORBA program that uses static invocation, which uses a client stub for the invocation and a
server skeleton for the service being invoked and is used when the interface of the object is known
at compile time.
This example requires a naming service, which is a CORBA service that allows CORBA objects
to be named by means of binding a name to an object reference. The name binding may be stored
in the naming service, and a client may supply the name to obtain the desired object reference. The
two options for Naming Services with Java include orbd, a daemon process containing a Bootstrap
Service, a Transient Naming Service,
To run this client-server application on the development machine:
You must use the -falloption with the idljcompiler to generate both client and server-side bindings.
This command line will generate the default server-side bindings, which assumes the POA
Inheritance server-side model.
The files generated by the idljcompiler for Hello.idl, with the -fallcommand lineoption, are:
o HelloPOA.java:
This abstract class is the stream-based server skeleton, providing basic CORBA functionality for the
server. It extends org.omg.PortableServer.Servant, andimplements the InvokeHandler interface and
the HelloOperations interface. The server class HelloImpl
extends HelloPOA.
o _HelloStub.java:
This class is the client stub, providing CORBA functionality for the client. It extends
org.omg.CORBA.portable.ObjectImpland implements
the Hello.javainterface.
o Hello.java:
This interface contains the Java version of IDL interface written. The Hello.java interface extends
org.omg.CORBA.Object, providing standard CORBA object functionality. It also extends the
HelloOperations interface and org.omg.CORBA.portable.IDLEntity.
o HelloHelper.java
This class provides auxiliary functionality, notably the narrow() method required to cast CORBA
object references to their proper types. The Helper class is responsiblefor reading and writing
the data type to CORBA streams, and inserting and extracting the data type from AnyS. The
Holder class delegates to the methods in the Helper class for reading
and writing.
o HelloHolder.java
This final class holds a public instance member of type Hello. Whenever the IDL typeis an outor
an inoutparameter, the Holder class is used. It provides operationsfor
org.omg.CORBA.portable.OutputStream and org.omg.CORBA.portable.InputStreamarguments,
which CORBA allows, but which do not map easilyto Java's semantics. The Holder class
delegates to the methods in the Helper class forreading and writing. It implements
org.omg.CORBA.portable.Streamable.
o HelloOperations.java
Page 24 of 60
This interface contains the methods sayHello() and shutdown(). The IDL-to-Javamapping puts all of
the operations defined on the IDL interface into this file, which is shared by both the stubs and
skeletons.
3. Compile the .java files, including the stubs and skeletons (which are in the directory
directory HelloApp). This step assumes the java/bindirectory is included in yourpath.
Note that 1050 is the port on which you want the name server to run. The -ORBInitialPort
argument is a required command-line argument.
Page 25 of 60
Page 26 of 60
Conclusion:
CORBA provides the network transparency; Java provides the implementation transparency.
CORBA complements the Java™ platform by providing a distributed object framework, servicesto
support that framework, and interoperability with other languages. The Java platform complements
CORBA by providing a portable, highly productive implementation environment. The combination
of Java and CORBA allows you to build more scalable and more capable applications than can be
built using the JDK alone.
ASSIGNMENT NO. 3
Page 27 of 60
Problem Statement:
Develop a distributed system, to find sum of N elements in an array by distributing N/n elements to n
number of processors MPI or OpenMP. Demonstrate by displaying the intermediate sums calculated
at different processors.
Tools / Environment:
Java Programming Environment, JDK1.8 or higher, MPI Library (mpi.jar), MPJ Express
(mpj.jar)
Theory:
Message passing is a popularly renowned mechanism to implement parallelism in applications;
it is also called MPI. The MPI interface for Java has a technique for identifying the user and helping
in lower startup overhead. It also helps in collective communication and could beexecuted
on both shared memory and distributed systems. MPJ is a familiar Java API for MPI
implementation. mpiJava is the near flexible Java binding for MPJ standards.
Currently developers can produce more efficient and effective parallel applications using message
passing.
A basic prerequisite for message passing is a good communication API. Java comes with various
ready-made packages for communication, notably an interface to BSD sockets, and the Remote
Method Invocation (RMI) mechanism. The parallel computing world is mainly concerned with
`symmetric' communication, occurring in groups of interacting peers. This symmetric model of
communication is captured in the successful Message Passing Interface standard (MPI).
The mpi.h file contains the definitions and declarations necessary for compiling an MPIprogram.
MPI_Init initializes the execution environment for MPI. It is a “share nothing” modality in which
the outcome of any one of the concurrent processes can in no way be influenced by the intermediate
results of any of the other processes. Command has to be called before any other MPI call is made,
and it is an error to call it more than a single time within the program. MPI_Finalizecleans up all
the extraneous mess that was first put into place by MPI_Init.
The principal weakness of this limited form of processing is that the processes on different nodes
run entirely independent of each other. It cannot enable capability or coordinated computing. To
get the different processes to interact, the concept of communicators is needed. MPI programs
are made up of concurrent processes executing at the same time that in almost all cases.
are also communicating with each other. To do this, an object called the “communicator” is
Page 28 of 60
provided by MPI. Thus the user may specify any number of communicators within an MPI
program, each with its own set of processes. “MPI_COMM_WORLD” communicator contains all
the concurrent processes making up an MPI program.
The size of a communicator is the number of processes that makes up the particular communicator.
The following function call provides the value of the number of processes of the specified
communicator:
int MPI_Comm_size(MPI_Comm comm, int _size).
The function "MPI_Comm_size” required to return the number of processes; int size.
MPI_Comm_size(MPI_COMM_WORLD,&size); This will put the total number of processes in
the MPI_COMM_WORLD communicator in the variable size of the process data context. Every
process within the communicator has a unique ID referred to as its “rank”. MPI system
automatically and arbitrarily assigns a unique positive integer value, starting with 0, to all the
processes within the communicator. The MPI command to determine the process rank is:
int MPI_Comm_rank (MPI_Comm comm, int _rank).
The sendfunction is used by the source process to define the data and establish the connectionof
the message. The send construct has the following syntax:
int MPI_Send (void _message, int count, MPI_Datatype datatype,int dest, int tag, MPI_Comm
comm)
The first three operands establish the data to be transferred between the source and destination
processes. The first argument points to the message content itself, which may be a simple scalar
or a group of data. The message data content is described by the next two arguments. The second
operand specifies the number of data elements of which the message is composed. The third
operand indicates the data type of the elements that make up the message.
The receive command (MPI_Recv) describes both the data to be transferred and theconnection
to be established. The MPI_Recv construct is structured as follows:
int MPI_Recv (void _message, int count, MPI_Datatype datatype,int source, int tag,
MPI_Comm comm, MPI_Status _status)
The source field designates the rank of the process sending the message.
Page 29 of 60
MPJ Express is an open source Java message passing library that allows application developers
to write and execute parallel applications for multicore processors and compute clusters /
clouds. The software is distributed under the MIT (a variant of the LGPL) license. MPJ Express
is a message passing library that can be used by application developers to execute their parallel
Java applications on compute clusters or network of computers.
MPJ Express is essentially a middleware that supports communication between individual
processors of clusters. The programming model followed by MPJ Express is Single Program
Multiple Data (SPMD).
The multicore configuration is meant for users who plan to write and execute parallel Java
applications using MPJ Express on their desktops or laptops which contains shared memory and
multicore processors. In this configuration, users can write their message passing parallel
application using MPJ Express and it will be ported automatically on multicore processors. We
except that users can first develop applications on their laptops and desktops using multicore
configuration, and then take the same code to distributed memory platforms
Page 30 of 60
Implementing the solution:
1. For implementing the MPI program in multi-core environment, we need to install MPJ
express library.
a. Download MPJ Express (mpj.jar) and unpack it.
b. Set MPJ_HOME and PATH environment variables:
c. export MPJ_HOME=/path/to/mpj/
d. export PATH=$MPJ_HOME/bin:$PATH
2. Write ScatterGather parallel Java program and save it as ScatterGather.java.
3. Compile a ScatterGather.javaparallel Java program
4. Running MPJ Express in the Multi-core Configuration.
Page 31 of 60
Compile: javac -cp $MPJ_HOME/lib/mpj.jar Asign2.java
(mpj.jar is inside lib folder in the downloaded MPJ Express)
Page 32 of 60
Conclusion :
There has been a large amount of interest in parallel programming using Java. mpj is an MPI binding
with Java along with the support for multicore architecture so that user can develop the code on it's own
laptop or desktop. This is an effort to develop and run parallel programs according to MPI standard.
Page 33 of 60
ASSIGNMENT NO.4
Problem Statement:
Implement Berkeley algorithm for clock synchronization.
Tools/Environment:
Python3, Eclipse IDE
Theory :
Distributed System is a collection of computers connected via the high-speed communication network.
In the distributed system, the hardware and software components communicate and coordinate their actions
by message passing. Each node in distributed systems can share their resources with other nodes. So, there
is need of proper allocation of resources to preserve the state of resources and help coordinate between the
several processes. To resolve such conflicts, synchronization is used. Synchronization in distributed
systems is achieved via clocks.
The physical clocks are used to adjust the time of nodes. Each node in the system can share its local time
with other nodes in the system. The time is set based on UTC (Universal Time Coordination). UTC is used
as a reference time clock for the nodes in the system.
The clock synchronization can be achieved by 2 ways: External and Internal Clock Synchronization.
External clock synchronization is the one in which an external reference clock is present. It is used
as a reference and the nodes in the system can set and adjust their time accordingly.
Internal clock synchronization is the one in which each node shares its time with other nodes and
all the nodes set and adjust their times accordingly.
Berkeley Algorithm
Berkeley’s Algorithm is a clock synchronization technique used in distributed systems. The algorithm
assumes that each machine node in the network either doesn’t have an accurate time source or doesn’t
possess a UTC server.
Page 34 of 60
Algorithm :
An individual node is chosen as the master node from a pool node in the network. This node is the main
node in the network which acts as a master and the rest of the nodes act as slaves. The master node
is chosen using an election process/leader election algorithm.
1. Master node periodically pings slaves nodes and fetches clock time at them using Cristian’s Algorithm
The diagram below illustrates how the master sends requests to slave nodes.
The diagram below illustrates how slave nodes send back time given by their system clock.
Master node calculates the average time difference between all the clock times received and the
clock time given by the master’s system clock itself. This average time difference is added to the current
time at the master’s system clock and broadcasted over the network.
Page 35 of 60
The diagram below illustrates the last step of Berkeley’s algorithm.
Scope of Improvement
Ignoring significant outliers in the calculation of average time difference
In case the master node fails/corrupts, a secondary leader must be ready/pre-chosen to take the place of
the master node to reduce downtime caused due to the master’s unavailability.
Instead of sending the synchronized time, master broadcasts relative inverse time difference, which leads
to a decrease in latency induced by traversal time in the network while the time of calculation at slave
node.
The code below is a python script that can be used to trigger a master clock server.
# program imitating a clock server
Page 36 of 60
Page 37 of 60
Page 38 of 60
# Python3 program imitating a client process
Page 39 of 60
How to run code in python:
Page 40 of 60
Conclusion :
Thus, we have implemented the Berkeley algorithm for clock synchronization.
ASSIGNMENT NO.5
Problem Statement:
Implement token ring based mutual exclusion algorithm.
Tools/Environment:
Java Programming Environment, JDK 1.8
Theory :
Process synchronization is the set of techniques that are used to coordinate execution among processes. For
example, a process may need to run to a certain point, at which point it will stop and wait for another
process to finish certain actions. A shared resource, such as a file or fields in a database, may require
exclusive access and processes have to coordinate among themselves to ensure that access to the resource
is fair and exclusive.
Page 41 of 60
The modification of a resource may be implemented as an atomic operation. That is, there might be a single
remote procedure call or web service that performs an operation on the resource. In this case, the server
may be able to handle access to the resource on its own. In many cases, however, there might be concurrent
requests on different servers that are competing for the same resource. There are also frequently situations
where resource access is not inherently atomic and a client will need to request a lock on the resource and
release it at a later time when all modifications are complete. Distributed transactions are an example
of a framework that relies on this.
In centralized systems, it was common to enforce exclusive access to shared code. Mutual exclusion was
accomplished through mechanisms such as test and set locks in hardware and semaphores, messages, and
condition variables in software.
Page 42 of 60
Figure 1. Centralized mutual exclusion
The central server algorithm simulates a single processor system. One process in the distributed system is
elected as the coordinator (Figure 1). When a process wants to enter a resource, it sends a request message
(Figure 1a) identifying the resource, if there are more than one, to the coordinator.
If nobody is currently in the section, the coordinator sends back a grant message (Figure 1b) and marks that
process as using the resource. If, however, another process has previously claimed the resource, the server
simply does not reply, so the requesting process is blocked. The coordinator keeps state on which process is
currently granted the resource and a which processes are requesting the resource. The list of requestors is a
first-come, first-served queue per resource. If some process has been granted access to the resource but has
not released it, any incoming grant requests are queued on the coordinator. When a coordinator receives
a release(R) message, it sends a grant message to the next process in the queue for resource R.
When a process is done with its resource, it sends a release message (Figure 1c) to the coordinator. The
coordinator then can send a grant message to the next process in its queue of processes requesting a
resource (if any).
This algorithm is easy to implement and verify. It is fair in that all requests are processed in order.
Unfortunately, it suffers from having a single point of failure. Another issue is that a process cannot
distinguish between being blocked (not receiving a grant because someone else is in the resource) and
not getting a response because the coordinator is down. From the coordinator’s side, the coordinator does
not know if a process using a resource has died, is in an infinite loop, or is simply taking a longer
time to release a resource. Moreover, a centralized server can be a potential bottleneck in systems with
a huge number of processes.
1. The ring is initialized by giving a token to process 0. The token circulates around the ring:
process n passes it to process (n+1) mod ringsize.
2. When a process acquires the token, it checks to see if it is is waiting to use the resource. If so, it uses
it and does its work. On exit, it passes the token to its neighboring process. In Figure 2, Process 1
had the token, completed its access to the resource, and is sending the token to its neighbor,
process 2.
3. If a process is not interested in grabbing the lock on the resource, it simply passes the token along to
its neighbor.
Only one process has the token, and hence the lock on the resource, at a time. Therefore, mutual exclusion
is guaranteed. Order is also well-defined, so starvation cannot occur. The biggest drawback of this
algorithm is that if a token is lost, it will have to be generated. Determining that a token is lost can be
difficult.
Page 44 of 60
.
Conclusion:
In this way Token Ring algorithm has been implemented. This algorithm is easy to implement and verify
but the biggest drawback of this algorithm is that if a token is lost, it will have to be generated. Determining
that a token is lost can be difficult.
Page 45 of 60
ASSIGNMENT NO.6
Problem Statement:
Implement Bully and Ring algorithm for leader election.
Tools / Environment:
Related Theory:
Election Algorithm:
1. Many distributed algorithms require a process to act as a coordinator.
2. The coordinator can be any process that organizes actions of other processes.
3. A coordinator may fail.
4. How is a new coordinator chosen or elected?
Assumptions:
Each process has a unique number to distinguish them. Processes know each other's
processnumber.
Bully Algorithm:
1. Receiver sends an OK message back to the sender to indicate that he is alive and will
takeover.
2. Eventually, all processes give up apart of one, and that one is the new coordinator.
3. The new coordinator announces its victory by sending all processes a CO-ORDINATOR
message telling them that it is the new coordinator.
C. If a process that was previously down comes back:
1. It holds an election.
2. If it happens to be the highest process currently running, it will win the election
and takeover the coordinators job.
Page 46 of 60
“Biggest guy" always wins and hence the name bully algorithm.
Ring Algorithm:
Initiation:
1. When a process notices that coordinator is not functioning:
2. Another process (initiator) initiates the election by sending "ELECTION" message
(containingits own process number)
Leader Election:
3. Initiator sends the message to it's successor (if successor is down, sender skips over it
and goesto the next member along the ring, or the one after that, until a running process
is located).
4. At each step, sender adds its own process number to the list in the message.
5. When the message gets back to the process that started it all: Message comes back to
initiator.In the queue the process with maximum ID Number wins.
Initiator announces the winner by sending another message around the ring.
Algorithm
Initiation:
Leader Election:
Page 47 of 60
A. For Bully Algorithm:
Page 48 of 60
Implementing the solution:
3. Getting input from User for number of Processes and store them into object of classes.
Page 49 of 60
Writing the source code:
Bully.java
Ring.java
Page 50 of 60
Compiling and Executing the solution:
Conclusion:
Election algorithms are designed to choose a coordinator. We have two election algorithms for
two different configurations of distributed system.
The Bully algorithm applies to system where every process can send a message to every other process
in the system .
The Ring algorithm applies to systems organized as a ring (logically or physically). In this algorithm we
assume that the link between the process are unidirectional and every process can message to the process
on its right only.
Page 51 of 60
ASSIGNMENT NO. 7
Problem Statement:
Create a simple web service and write any distributed application to consume the web service
Tools / Environment:
Related Theory:
Web Service:
A web service can be defined as a collection of open protocols and standards for exchanging
information among systems or applications.
1. SOAP: SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry
standard protocol for designing and developing web services. Since it’s XML based, it’s
platform and language independent. So, our server can be based on JAVA and client can
be on .NET, PHP etc. and vice versa.
2. REST: REST (Representational State Transfer) is an architectural style for developing web
services. It’s getting popularity recently because it has small learning curve when compared
to SOAP. Resources are core concepts of Restful web services and they are uniquely
identified by their URIs.
Service Provider is the program that implements the service agreed for the web service and
exposes the service over the internet/intranet for other applications to interact with.
Page 52 of 60
Service Requestor is the program that interacts with the web service exposed by the Service
Provider. It makes an invocation to the web service over the network to the Service Provider and
exchanges information.
Service Registry acts as the directory to store references to the web services.
The following are the steps involved in a basic SOAP web service operational behavior:
1. The client program that wants to interact with another application prepares its request
content as a SOAP message.
2. Then, the client program sends this SOAP message to the server web service as an HTTP
POST request with the content passed as the body of the request.
3. The web service plays a crucial role in this step by understanding the SOAP request and
converting it into a set of instructions that the server program can understand.
4. The server program processes the request content as programmed and prepares the output
as the response to the SOAP request.
5. Then, the web service takes this response content as a SOAP message and reverts to the
SOAP HTTP request invoked by the client program with this response.
6. The client program web service reads the SOAP response message to receive the
outcome of the server program for the request content it sent as a request.
Simple Object Access Protocol (SOAP) is an XML-based protocol for accessing web services.
It is a W3C recommendation for communication between two applications, and it is a platform-
and language-independent technology in integrated distributed applications.
While XML and HTTP together make the basic platform for web services, the following are the
key components of standard SOAP web services:
Page 53 of 60
RESTful web services
REST stands for Representational State Transfer. RESTful web services are considered a
performance-efficient alternative to the SOAP web services. REST is an architectural style, not a
protocol. Refer to the following diagram:
Page 54 of 60
While both SOAP and RESTful support efficient web service development, the difference
between these two technologies can be checked out in the following table :
Java provides it’s own API to create both SOAP as well as RESTful web services.
1. JAX-WS: JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based
Java API to build web services server and client application.
2. JAX-RS: Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST
web services. JAX-RS uses annotations to simplify the development and deployment of
web services.
Both of these APIs are part of standard JDK installation, so we don’t need to add any jars to
work with them.
Students are required to implement both i.e. using SOAP and RESTful APIs.
Page 56 of 60
Page 57 of 60
Compiling and Executing the solution:
Page 58 of 60
PICT, BE-IT Laboratory Practice - V
Conclusion:
This assignment, described the Web services approach to the Service Oriented
architecture concept. Also, described the Java APIs for programming Web
services and demonstrated examples of their use by providing detailed step-
by-step examples of how to program Web services in Java.
59
PICT, BE-IT Laboratory Practice - V
ASSIGNMENT NO.8
Problem Statement:
Mini Project: A Distributed Application for Interactive Multiplayer Games
Theory:
As the gaming industry continues to grow in size, the need to create a unique and dynamic
userexperience has become even more mandatory. Because of its fandom, businesses have to
maximizethe multiplayer gaming experience to drive customer acquisition and retention.
However, companies are faced with a number of obstacles when trying to scale multiplayer
games, all of which can be solved through Redis.
Personalized interactions and high-speed reactions are at the heart of creating a unique
userexperience. Redis provides game publishers with a powerful database that can support low-
latency gaming use cases. Recently a Launchpad App built a unique application that could have
only beendeployed by Redis due to its unmatched speed in transmitting data.
This is crucial because participants play from all around the world. Interactions
between players must be executed in real-time to support gameplay, requiring the latency to be
less than onemillisecond.
Students can form a group of 3 to 4 students and can develop the Interactive
MultiplayerGame.
Students must use Open-Source Operating Systems, tools, Multi-core CPU
supportingVirtualization and Multi-Threading.
https://redis.com/blog/how-to-build-a-real-time-geo-distributed-multiplayer-top-
down-arcade-shooting-game-using-redis/
https://www.smashingmagazine.com/2021/10/real-time-multi-user-game/
https://ably.com/blog/peer-to-peer-game-with-pub-sub
60