0% found this document useful (0 votes)
14 views16 pages

Java RMI and CORBA Examples

Distributed System Book PDF
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

Java RMI and CORBA Examples

Distributed System Book PDF
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Assignment 1

Input :

import [Link];
import [Link];

public class ChatClient {


public static void main(String[] args) {
try {
ChatInterface chat = (ChatInterface)
[Link]("rmi://localhost:5000/chat");

Scanner scanner = new Scanner([Link]);


[Link]("Enter your name: ");
String name = [Link]();

while (true) {
[Link]("Message: ");
String msg = [Link]();
if ([Link]("exit")) break;

String reply = [Link](name, msg);


[Link]("Server: " + reply);
}

[Link]();
} catch (Exception e) {
[Link]("Client Exception: " + [Link]());
[Link]();
}
}
}

import [Link];
import [Link];

public interface ChatInterface extends Remote {


String sendMessage(String name, String message) throws
RemoteException;
}

import [Link];
import [Link];
import [Link];

public class ChatServer extends UnicastRemoteObject implements


ChatInterface {

protected ChatServer() throws RemoteException {


super();
}

@Override
public synchronized String sendMessage(String name, String
message) {
String reply = name + ": " + message;
[Link]("Received -> " + reply);
return "Server received message: " + reply;
}
public static void main(String[] args) {
try {
[Link]("rmi://localhost:5000/chat", new ChatServer());
[Link]("Server started on port 5000...");
} catch (Exception e) {
[Link]("Server Exception: " + [Link]());
[Link]();
}
}
}

Output :

Server Console:
----------------
Server started on port 5000...
Received -> Alice: Hello
Received -> Bob: Hi there!

Client Console:
----------------
Enter your name: Alice
Message: Hello
Server: Server received message: Alice: Hell
Assignment 2

Input :

interface Calculator {
float add(in float a, in float b);
float subtract(in float a, in float b);
float multiply(in float a, in float b);
float divide(in float a, in float b);
};
public class CalculatorImpl extends CalculatorPOA {
public float add(float a, float b) {
return a + b;
}
public float subtract(float a, float b) {
return a - b;
}
public float multiply(float a, float b) {
return a * b;
}
public float divide(float a, float b) {
return b != 0 ? a / b : 0;
}
}
import [Link].*;
import [Link].*;

public class Client {


public static void main(String args[]) {
try {
ORB orb = [Link](args, null);
[Link] objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef =
[Link](objRef);
Calculator calc =
[Link](ncRef.resolve_str("Calculator"));

[Link]("Add: " + [Link](10, 5));


[Link]("Subtract: " + [Link](10, 5));
[Link]("Multiply: " + [Link](10, 5));
[Link]("Divide: " + [Link](10, 5));
} catch (Exception e) {
[Link]("ERROR: " + e);
[Link]();
}
}
}
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

public class Server {


public static void main(String args[]) {
try {
ORB orb = [Link](args, null);
POA rootpoa =
[Link](orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();

CalculatorImpl calcImpl = new CalculatorImpl();


[Link] ref =
rootpoa.servant_to_reference(calcImpl);
Calculator href = [Link](ref);
[Link] objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef =
[Link](objRef);
NameComponent path[] = ncRef.to_name("Calculator");
[Link](path, href);

[Link]("Calculator Server ready...");


[Link]();
} catch (Exception e) {
[Link]("ERROR: " + e);
[Link]();
}
}
}

Output :

Server Console:
----------------
Calculator Server ready...

Client Console:
----------------
Add: 15.0
Subtract: 5.0
Multiply: 50.0
Divide: 2.0
Assignment 3

Input :

import [Link];

public class ArraySumMPI {


public static void main(String[] args) {
int n = 8;
int[] array = {1, 2, 3, 4, 5, 6, 7, 8};
int processors = 4;
int elementsPerProcessor = n / processors;
int[] intermediateSums = new int[processors];
int totalSum = 0;

for (int i = 0; i < processors; i++) {


int localSum = 0;
for (int j = i * elementsPerProcessor; j < (i + 1) *
elementsPerProcessor; j++) {
localSum += array[j];
}
intermediateSums[i] = localSum;
[Link]("Processor " + i + " calculated sum = " +
localSum);
totalSum += localSum;
}

[Link]("Total sum = " + totalSum);


}
}

Output :
Processor 0 calculated sum = 6
Processor 1 calculated sum = 10
Processor 2 calculated sum = 14
Processor 3 calculated sum = 18
Total sum = 48
Assignment 4

Input :

import [Link].*;

public class BerkeleyClockSync {


public static void main(String[] args) {
int[] clocks = {1000, 1015, 980, 1020}; // simulated clock times
int master = clocks[0];
int totalDiff = 0;
[Link]("Clocks before sync:");
for (int c : clocks) [Link](c);

for (int i = 1; i < [Link]; i++) {


totalDiff += clocks[i] - master;
}

int avgDiff = totalDiff / [Link];


[Link]("\nAverage difference: " + avgDiff);

for (int i = 0; i < [Link]; i++) {


if (i != 0) {
clocks[i] -= ((clocks[i] - master) - avgDiff);
}
}

[Link]("\nClocks after sync:");


for (int c : clocks) [Link](c);
}
}

Output :

Clocks before sync:


1000
1015
980
1020

Average difference: 8

Clocks after sync:


1000
1008
1008
1008
Assignment 5

Input :

import [Link];

public class TokenRing {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = 5;
int token = 0;
int request;

while (true) {
[Link]("Enter process (0 to " + (n - 1) + ")
requesting CS or -1 to exit: ");
request = [Link]();
if (request == -1) break;

for (int i = token; i != request; i = (i + 1) % n) {


[Link]("Token passed from " + i + " to " + ((i + 1)
% n));
}

[Link]("Process " + request + " entered Critical


Section.");
[Link]("Process " + request + " exited Critical
Section.");
token = (request + 1) % n;
}
[Link]();
}
}

Output :

Enter process (0 to 4) requesting CS or -1 to exit:


2
Token passed from 0 to 1
Token passed from 1 to 2
Process 2 entered Critical Section.
Process 2 exited Critical Section.

Enter process (0 to 4) requesting CS or -1 to exit:


-1
Assignment 6

Input :

public class BullyAlgorithm {


public static void main(String[] args) {
int[] processes = {1, 2, 3, 4, 5};
int crashed = 5;
int initiator = 2;

[Link]("Process " + crashed + " has crashed.");


[Link]("Process " + initiator + " initiates election.");
for (int i = initiator + 1; i < [Link]; i++) {
[Link]("Election message sent to process " +
processes[i]);
}

[Link]("Process " + (crashed - 1) + " is elected as


leader.");
}
}
public class RingAlgorithm {
public static void main(String[] args) {
int[] processes = {0, 1, 2, 3, 4};
int initiator = 2;
int max = processes[initiator];

[Link]("Ring election initiated by Process " +


initiator);
for (int i = 1; i < [Link]; i++) {
int idx = (initiator + i) % [Link];
[Link]("Message passed to " + processes[idx]);
if (processes[idx] > max) max = processes[idx];
}

[Link]("Leader elected: Process " + max);


}
}
Output :

Bully Algorithm:
Process 5 has crashed.
Process 2 initiates election.
Election message sent to process 3
Election message sent to process 4
Process 4 is elected as leader.

Ring Algorithm:
Ring election initiated by Process 2
Message passed to 3
Message passed to 4
Message passed to 0
Message passed to 1
Leader elected: Process 4
Assignment 7

Input :
import [Link];
import [Link];
import [Link];

public class Client {


public static void main(String[] args) throws Exception {
URL url = new URL("[Link]
QName qname = new QName("[Link]
"HelloServiceService");
Service service = [Link](url, qname);
HelloService hello = [Link]([Link]);

[Link]([Link]("Alice"));
}
}
import [Link];
import [Link];

@WebService
public class HelloService {
@WebMethod
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}

Output :

Hello, Alice!
Assignment 8

Input :

import [Link].*;

public class MultiplayerGame {


static Map<String, Integer> players = new HashMap<>();

public static void main(String[] args) {


[Link]("Player1", 0);
[Link]("Player2", 0);

Random rand = new Random();


for (int round = 1; round <= 3; round++) {
[Link]("Round " + round);
for (String player : [Link]()) {
int score = [Link](10);
[Link](player, [Link](player) + score);
[Link](player + " scored: " + score);
}
}

[Link]("\nFinal Scores:");
for (String player : [Link]()) {
[Link](player + ": " + [Link](player));
}
}
}
Output :

Round 1
Player1 scored: 4
Player2 scored: 7
Round 2
Player1 scored: 6
Player2 scored: 3
Round 3
Player1 scored: 5
Player2 scored: 8

Final Scores:
Player1: 15
Player2: 18

Common questions

Powered by AI

Java RMI enhances the chat application's functionality by enabling remote communication over a network, allowing the server and clients to interact across different machines seamlessly. Unlike a local application where components are confined to the same environment, RMI abstracts the complexity of network programming by enabling method calls across the network as if they were local calls. This distributed architecture allows multiple clients to connect to the server, facilitating a many-to-one relationship that supports scalable and flexible chat operations .

The token ring protocol's scalability in Java is impacted by the linear nature of the token passing mechanism. As the number of processes increases, the time taken for the token to circulate through all processes also increases linearly. Each process must wait for the token to traverse the entire ring before gaining access to its critical section. With more processes, the frequency of access to the critical section decreases for each process, potentially leading to increased wait times and reduced overall throughput. This linear scalability limitation is inherent to the token ring design, implying that significant performance degradation can occur as process numbers grow .

The multiplayer game in Java utilizes the Random class to generate pseudo-random scores for players in each round, simulating variability and uncertainty typical in games. The Map data structure, particularly the HashMap, stores player names as keys and their cumulative scores as values. For each round, scores are updated by adding the newly generated random number to the existing value associated with each player. This combination of Random and Map facilitates efficient score tracking and updates while supporting dynamic addition and retrieval operations, demonstrating practical use in game development .

The array sum computation using MPI-like simulation in Java involves dividing an array among multiple processors, each computing a partial sum. Although specific error handling is not explicitly detailed in the given implementation, potential mechanisms include using exception handling (try-catch blocks) to manage out-of-bound errors during array slicing or incorrect processor index access. As MPI is designed for distributed computing, robust error handling could include monitoring processor availability, handling communication faults, and ensuring intermediate sums integrity through checksums or validations, thereby preventing erroneous totals .

Berkeley Clock Synchronization is an algorithm for synchronizing clocks in a distributed system. In the provided implementation, the master clock (first clock) calculates the average difference by taking the difference between each clock and itself and summing these differences. The average difference is then computed by dividing the total difference by the number of clocks. Non-master clocks adjust their time by applying the difference between their current time and the master time, adjusted by the average difference, ensuring synchronized clocks throughout the network .

In the Ring Election Algorithm, each process in the ring topology can initiate an election. Upon initiation, the process sends a message to its successor indicating the election has started. If a process receives a message with a higher ID than its own, it forwards this message. The process with the highest ID, once it receives its own ID again, declares itself the leader. In this implementation, process 2 initiates the election, passes messages through the ring, and process 4 is ultimately elected as the leader because it has the highest ID .

The Token Ring Algorithm ensures mutual exclusion by circulating a 'token' among processes arranged in a logical ring. Only the process holding the token can enter its critical section. When a process wants to access the critical section, it must wait for the token. The token is passed along predefined paths from one process to the next, thus preventing concurrent access. The algorithm maintains a single token at all times and, upon completion of the critical section, the holding process passes the token to the next process in line, as demonstrated by the token passing process .

The chat application uses Java RMI (Remote Method Invocation) for client-server communication. The client, as per the 'ChatClient' class, looks up a remote object 'ChatInterface' through the RMI registry using the Naming.lookup() method. The server, defined in the 'ChatServer' class, implements the 'ChatInterface' by extending 'UnicastRemoteObject'. It listens on the specified RMI URL, 'rmi://localhost:5000/chat', and processes messages from the client by returning a confirmation message prefixed with 'Server received message'. The client sends messages to the server using the 'sendMessage' method, which the server then prints and responds to accordingly .

In the ArraySumMPI program, dividing tasks between processors increases efficiency by leveraging parallel processing to perform computations concurrently. By distributing array segments equally among processors, each processor computes a segment's sum independently, reducing overall computation time when compared to a single-threaded approach. However, the performance gain is contingent on balanced workload distribution and inter-process communication overhead. If communication overhead is minimized and the workload is well-balanced, parallel execution significantly enhances performance, handling larger datasets more efficiently while maintaining scalability through processor utilization .

The Bully Algorithm and the Ring Algorithm both address leader election in distributed systems but differ in operation. The Bully Algorithm requires processes to send election messages to all higher-numbered processes when a leader is found to be unavailable. Each process with a higher identifier returns response messages until the highest-numbered process is elected as the leader. It uses more messages, which may increase overhead. In contrast, the Ring Algorithm circulates messages through a logical ring structure where each process forwards the message to the next. The process with the highest identifier is elected when the message completes a full cycle. The ring structure limits message propagation, reducing overhead, but may potentially take longer due to sequential message-passing .

You might also like