Dis Fromnt Merged

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Distributed Systems

Course code: CSI3012


Slot: L9 + L10
Winter Semester 2023-24

NAME: SHEETHLL.P
REG NUM: 20MID0206
CLASS NUMBER: VL2023240504729
GUIDED BY: Dr AYYASAMY S

DIGITAL ASSIGNMENT- 3
(LAB)
Guwstion 3 :
a Remste Posedse Call (epe::
Paebe Batewaut :
The qupuided Sava ode inglemais.
Te syste cowmpmes
Bankew) and a clied cEaubtieut) tht'
|Conmunicate eve the wtusok
pmoivide ad cowgume banking seutees

alane, dqenting
te proeues

wnnicahon hotoot thal allous a clut


siuroke proada huhios
Ewe as
wwe lal

Q. RPC
RPC
the
sewer aud cewe e'sslts
dtaie.

Baukae sinste procedlanes


and uikdsao
getBalaue,
4- Remde Procedune Twekhen: Tue
EakCieutdlas ciwshes aemote procede

5. Kower side Implemeutahin: The


Bank Sevea class

ouates au sinstae Bauk Sewiefuple, luich


paida uinplamutatio
ooatons.
6. knuegtion taudling: e ode handles
naptions uh as Rumaebxoaphion , lic
bonnuuncatisn a ewerr side
gPC townication
Uee wessages and
dack troaus
Euk Bersie Lnupl, usleich preseuts
|dtheke - side inplawation kaukig
pouztins.
prouded y Eauk SosiceInd do te dest by
acussible

a. cliut Itenahiou:

the sewee sinste procdwes

#. sends RPcqesa o te sesve

preses
atian lased on te
sutome
PROGRAM:
BankServer.java
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.Naming;

public class BankServer {


public static void main(String args[]) {
try {
// Create an instance of the implementation class
BankService bankService = new BankServiceImpl();

// Bind the remote object's stub in the registry


Naming.rebind("BankService", bankService);

System.out.println("Bank server ready");


} catch (Exception e) {
System.err.println("Bank server exception: " + e.toString());
e.printStackTrace();
}
}
}

BankClient.java:
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.Naming;

public class BankClient {


public static void main(String args[]) {
try {
// Lookup the remote object from the registry
BankService bankService = (BankService)
Naming.lookup("//localhost/BankService");

// Example usage
String accountNumber = "123456";
System.out.println("Balance for account " + accountNumber + ": " +
bankService.getBalance(accountNumber));
bankService.deposit(accountNumber, 500);
System.out.println("New balance after deposit: " +
bankService.getBalance(accountNumber));
bankService.withdraw(accountNumber, 200);
System.out.println("New balance after withdrawal: " +
bankService.getBalance(accountNumber));
} catch (Exception e) {
System.err.println("Bank client exception: " + e.toString());
e.printStackTrace();
}
}
}

BankService.java:
import java.rmi.Remote;
import java.rmi.RemoteException;

// Remote interface defining banking operations


public interface BankService extends Remote {
double getBalance(String accountNumber) throws RemoteException;
void deposit(String accountNumber, double amount) throws RemoteException;
void withdraw(String accountNumber, double amount) throws RemoteException;
}

BankServiceImpl.java:
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Map;
import java.util.HashMap;

public class BankServiceImpl extends java.rmi.server.UnicastRemoteObject


implements BankService {
// Simulated database to store account balances
private Map<String, Double> accounts;

public BankServiceImpl() throws RemoteException {


// Initialize the database
accounts = new HashMap<>();
accounts.put("123456", 1000.0); // Sample account with initial balance
1000
}

public double getBalance(String accountNumber) throws RemoteException {


Double balance = accounts.get(accountNumber);
if (balance == null) {
throw new RemoteException("Account not found");
}
return balance;
}

public void deposit(String accountNumber, double amount) throws


RemoteException {
Double balance = accounts.get(accountNumber);
if (balance == null) {
throw new RemoteException("Account not found");
}
accounts.put(accountNumber, balance + amount);
}

public void withdraw(String accountNumber, double amount) throws


RemoteException {
Double balance = accounts.get(accountNumber);
if (balance == null) {
throw new RemoteException("Account not found");
}
if (balance < amount) {
throw new RemoteException("Insufficient balance");
}
accounts.put(accountNumber, balance - amount);
}
}

INPUT:
OUTPUT:
b, LAMPORT ALsORITHM :
Peotlem Shateast:
The pueblem tatament addensec in t
Jowa code is
lencsion
|amget nswes
that oe

secton waletme,
onneent auiss
could sleacd to data inoiistuy
onditios

Piatibited
sbibeted
owmeate
laes to sdhcal echows ode.
. utusl Frlusien: he woe
adduud stichual enlusion,
Pne site can
uteal sechon at time, prvtiY
coneusnett enetion.
3.

lcinglameuts
tual enhsien
Jampot& algoritln Wses

aress, poesns.
S alleus

Rugueting anby inb uteal sechon:


into tu
ihtal sechon a

ti tu vihal
sechon, t entubs ub eihcal eehon code
3.Eriting wukal sechon :
vihcal sechon
andl
4 ttandlg mesagea:
.k. The uede
simlates
nhange ietven sites for tommuwucahion
REqUeeT
RELEASE mn
And, ueerclination.
5. Tinmeatanps:
imastamgs ae

pontal ditibtel
sites.
PROGRAM:
import java.util.PriorityQueue;

class Site {
int id;
int timestamp;

public Site(int id, int timestamp) {


this.id = id;
this.timestamp = timestamp;
}
}

class Lamport {
int numSites;
int[] requestQueue;
PriorityQueue<Site> priorityQueue;

public Lamport(int numSites) {


this.numSites = numSites;
this.requestQueue = new int[numSites];
this.priorityQueue = new PriorityQueue<>((s1, s2) -> {
if (s1.timestamp != s2.timestamp) {
return Integer.compare(s1.timestamp, s2.timestamp);
} else {
return Integer.compare(s1.id, s2.id);
}
});
}

public synchronized void enterCriticalSection(int siteId, int timestamp) {


// Send REQUEST message to all other sites
System.out.println("Site " + siteId + " requests to enter critical
section with timestamp " + timestamp);
for (int i = 0; i < numSites; i++) {
if (i != siteId) {
// Simulating message exchange
receiveRequest(siteId, timestamp, i);
}
}

// Place the request on requestQueue


requestQueue[siteId] = timestamp;

// Wait until the site can enter the critical section


while (!canEnterCriticalSection(siteId)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("Site " + siteId + " enters critical section.");


}

private synchronized void receiveRequest(int senderId, int


senderTimestamp, int receiverId) {
// Simulating receiving REQUEST message
System.out.println("Site " + receiverId + " receives REQUEST message
from site " + senderId + " with timestamp "
+ senderTimestamp);
priorityQueue.add(new Site(senderId, senderTimestamp));
requestQueue[senderId] = senderTimestamp;

// Send REPLY message to sender


// Simulating message exchange
receiveReply(receiverId, senderId, senderTimestamp);
}

private synchronized void receiveReply(int senderId, int receiverId, int


timestamp) {
// Simulating receiving REPLY message
System.out.println(
"Site " + receiverId + " sends REPLY message to site " +
senderId + " with timestamp " + timestamp);
requestQueue[senderId] = timestamp;
notifyAll();
}

private boolean canEnterCriticalSection(int siteId) {


// Check if all requests with smaller timestamp have been received
for (int i = 0; i < numSites; i++) {
if (i != siteId && requestQueue[i] < requestQueue[siteId]) {
return false;
}
}
return true;
}

public synchronized void exitCriticalSection(int siteId) {


// Remove request from requestQueue
requestQueue[siteId] = 0;
System.out.println("Site " + siteId + " exits critical section.");
// Send RELEASE message to all other sites
for (int i = 0; i < numSites; i++) {
if (i != siteId) {
// Simulating message exchange
receiveRelease(siteId, i);
}
}
}

private synchronized void receiveRelease(int senderId, int receiverId) {


// Simulating receiving RELEASE message
System.out.println("Site " + receiverId + " receives RELEASE message
from site " + senderId);
requestQueue[senderId] = 0;
notifyAll();
}
}

public class lamp {


public static void main(String[] args) {
int numSites = 5; // Change as per the number of sites in the system
Lamport lamport = new Lamport(numSites);

// Example usage
int siteId = 0; // Assuming site ID starts from 0
int timestamp = 1; // Initial timestamp
lamport.enterCriticalSection(siteId, timestamp);
// Critical section code here
lamport.exitCriticalSection(siteId);
}
}

INPUT & OUTPUT:


Ci RICART AGRANALA AKGORITHM:

Peobla

puovided Tava code uhal


Lenulusion clitribuded syten wsng
the Riant -yrawla goitn. hutual
Can
nclinon enues tat
eihcalLutien cade ata tme
uonweut aws
pYocesses oich cauld lead co datu incouistuuy

code
s. Riant -shuauala tgoitm; fautual
niluson distnbuted iachinig
gesnisim -bascd aproak,uohere a'ate
REGUEST nsages to ohun sites to oltain
sends
pessmiasior
eet oden to ed aue Sllauy 4.
5.Tineetamps:
lat
4:
to
sall esags REPLY ns ik acode,
iieno indicating ites, ethur all om
es eEPLY ucawes site
othuu all to
secfon ihoal
,?
PROGRAM:
import java.util.ArrayList;
import java.util.List;

class Message {
int senderId;
MessageType type;
int timestamp;

public Message(int senderId, MessageType type, int timestamp) {


this.senderId = senderId;
this.type = type;
this.timestamp = timestamp;
}
}

enum MessageType {
REQUEST,
REPLY
}

class Site {
int siteId;
boolean requestingCS;
int timestamp;
List<Site> deferredRequests;

public Site(int siteId) {


this.siteId = siteId;
this.requestingCS = false;
this.timestamp = 0;
this.deferredRequests = new ArrayList<>();
}

public void requestCS(List<Site> sites) {


timestamp++;
requestingCS = true;
System.out.println("Site " + siteId + " requests access to the
critical section.");

Message request = new Message(siteId, MessageType.REQUEST, timestamp);


for (Site site : sites) {
if (site != this) {
site.receiveRequest(request, this);
}
}
}
public void receiveRequest(Message request, Site sender) {
System.out.println("Site " + siteId + " receives REQUEST from Site " +
sender.siteId + ".");
if (!requestingCS || (request.timestamp < timestamp)
|| (request.timestamp == timestamp && request.senderId <
siteId)) {
System.out.println("Site " + siteId + " sends REPLY to Site " +
sender.siteId + ".");
sendReply(sender);
} else {
deferredRequests.add(sender);
}
}

public void sendReply(Site receiver) {


Message reply = new Message(siteId, MessageType.REPLY, 0);
receiver.receiveReply(reply);
}

public void receiveReply(Message reply) {


// Do nothing for now
}

public void enterCS() {


if (deferredRequests.isEmpty()) {
System.out.println("Site " + siteId + " enters the critical
section.");
leaveCS();
}
}

public void leaveCS() {


requestingCS = false;
timestamp++;
System.out.println("Site " + siteId + " leaves the critical
section.");
for (Site site : deferredRequests) {
sendReply(site);
}
deferredRequests.clear();
}
}

public class ric {


public static void main(String[] args) {
// Create sites
List<Site> sites = new ArrayList<>();
for (int i = 0; i < 5; i++) {
sites.add(new Site(i));
}

// Simulate one site requesting critical section


sites.get(0).requestCS(sites);
// Simulate another site requesting critical section
sites.get(1).requestCS(sites);
// Simulate a site leaving critical section
sites.get(0).leaveCS();
}
}

INPUT & OUTPUT:

You might also like