You are on page 1of 17

# mutex.

java
This program implements Maekawa's voting algorithm for mutual exclusion
as described in R. Chow et al, "Distributed Operating Systems &
Algorithms".

## 26-Jan-1999: created by Thomas Prokosch (tp) based on

Christian Mittermaier's (cm) formalized model
31-Jan-1999: changed voting district
*/

import daj.*;
import Prog;
import java.lang.Math;

## public class mutex extends Application {

Node proc[];
static final int SQPROCS=4; /* square root of the number of
procs */
static final int NOPROCS=SQPROCS*SQPROCS;

## /* starter of program when run as an applet */

public static void main(String[] args) {
new mutex().run();
}

## /* starter of program when run as an application */

public mutex() {
super("Maekawa's Voting Algorithm", 400, 400);
proc=new Node[NOPROCS];
}

/* construct creates the nodes and the links between them randomly */
public void construct() {
int i, j;
setChannelWidth(2);

## /* create the processors */

for (i=0; i<NOPROCS; i++) {
/* place the procs on the screen */
proc[i]=node(new Prog(i, SQPROCS), String.valueOf(i),
80*(i%SQPROCS)+80, 80*(i/SQPROCS)+80);
}

## /* create links between the given processors */

for (i=0; i<NOPROCS-1; i++) {
if (i<NOPROCS-SQPROCS) { /* link vertically */
}
if (i%SQPROCS<SQPROCS-1) { /* link horizontally */
}
}
}

## public String getText() {

return "Maekawa's Voting Algorithm\n\n" +
"This program implements Maekawa's\n"+
algorithm, an application may\n"+
"enter a critical region.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
boolean closed=false,inputFromAll=false;
List<String> data;
Server()
{
t = new ArrayList<clientThread>();
data= new ArrayList<String>();
}
public static void main(String args[])
{
Socket clientSocket = null;
ServerSocket serverSocket = null;
int port_number=1111;
Server ser=new Server();
try
{
serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{
System.out.println(e);
}
while(!ser.closed)
{
try
{
clientSocket = serverSocket.accept();
System.out.println("\nNow Total clients are : "+(ser.t).size());
th.start();
}
catch (IOException e)
{
}
}

try
{
serverSocket.close();
}
catch(Exception e1)
{
}
}
}
{
DataInputStream is = null;
String line;
String destClient="";
String name;
PrintStream os = null;
Socket clientSocket = null;
String clientIdentity;
Server ser;
public clientThread(Server ser,Socket clientSocket)
{
this.clientSocket=clientSocket;
this.ser=ser;
}
public void run()
{
try
{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
clientIdentity=name;
os.println("Welcome "+name+" to this 2 Phase Application.\nYou will receive a vote Request
now...");
os.println("VOTE_REQUEST\nPlease enter COMMIT or ABORT to proceed : ");
for(int i=0; i<(ser.t).size(); i++)
{
if((ser.t).get(i)!=this)
{
((ser.t).get(i)).os.println("---A new user "+name+" entered the Appilcation---");
}
}
while (true)
{
if(line.equalsIgnoreCase("ABORT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : ABORT\n\nSince aborted we will not wait
for inputs from other clients.");
System.out.println("\nAborted....");
for(int i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_ABORT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
if(line.equalsIgnoreCase("COMMIT"))
{
System.out.println("\nFrom '"+clientIdentity+"' : COMMIT");
if((ser.t).contains(this))
{
(ser.data).set((ser.t).indexOf(this), "COMMIT");
for(int j=0;j<(ser.data).size();j++)
{
if(!(((ser.data).get(j)).equalsIgnoreCase("NOT_SENT")))
{
ser.inputFromAll=true;
continue;
}

else
{
ser.inputFromAll=false;
System.out.println("\nWaiting for inputs from other clients.");
break;
}
}
if(ser.inputFromAll)
{
System.out.println("\n\nCommited....");
for(int i=0; i<(ser.t).size(); i++)
{
((ser.t).get(i)).os.println("GLOBAL_COMMIT");
((ser.t).get(i)).os.close();
((ser.t).get(i)).is.close();
}
break;
}
}//if t.contains
}//commit
}//while
ser.closed=true;
clientSocket.close();
}
catch(IOException e)
{
};}}

2. Client.java:
import java.io.*;
import java.net.*;
public class Client implements Runnable
{
static Socket clientSocket = null;
static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;
public static void main(String[] args)
{
int port_number=1111;
String host="localhost";
try
{
clientSocket = new Socket(host, port_number);

os = new PrintStream(clientSocket.getOutputStream());
is = new DataInputStream(clientSocket.getInputStream());
}
catch (Exception e)
{
System.out.println("Exception occurred : "+e.getMessage());
}
if (clientSocket != null && os != null && is != null)
{
try
{
while (!closed)
{
}
os.close();
is.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}
}
} public void run()
{
String responseLine;
try
{
while ((responseLine = is.readLine()) != null)
{
System.out.println("\n"+responseLine);
if (responseLine.equalsIgnoreCase("GLOBAL_COMMIT")==true ||
responseLine.equalsIgnoreCase("GLOBAL_ABORT")==true )
{
break;
}
}
closed=true;
}
catch (IOException e)
{
System.err.println("IOException: " + e);
}}}

QUESTION NO N0 3

import
java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RingElection {

## int coord; /* Initialize it to the ID of the Co-Ordinator */

int curPid; /* Initialize it to the ID of the current node */
int n; /* Initialize it to the number of nodes */
/* flag variables */
int elNum = 1;
int c_alive = -1;

## String[] address; /* Initialize the array to the IP addresses of the

next occuring nodes in order */
String[] sAddress; /* Initialize the array to the IP addresses of all
the nodes from node 1 */
String cdAddress; /* Initialize it to the IP address of the Co-
Ordinator */
String address1; /* Initiliaze it to the IP address of the current
node */
int cdPort; /* Initialize it to the port number of the Co-
Ordinator */
int[] port; /* Initialize the array to the port number of the
next occuring nodes in order */
int port1; /* Initialize it to a port number */
int port2; /* Initialize it to a port number */
int port3; /* Initialize it to a port number */
int port4; /* Initialize it to a port number */
int port5; /* Initialize it to a port number */
int port6; /* Initialize it to a port number */
int[] sPorts; /* Initialize it to port numbers of the other nodes
*/
int[] cPorts; /* Initialize it to port numbers of the other nodes
*/
int[] mPorts; /* Initialize it to port numbers of the other nodes
*/
DatagramSocket socket1 = new DatagramSocket(port1);
DatagramSocket socket2 = new DatagramSocket(port2);
DatagramSocket socket3 = new DatagramSocket(port3);
DatagramSocket socket4 = new DatagramSocket(port4);
DatagramSocket socket5 = new DatagramSocket(port5);
DatagramSocket socket6 = new DatagramSocket(port6);

## Queue<String> queue = new LinkedList<String>();

String cdMsg = "COORDNTR ";
String okMsg = "OKMESAGE ";
String elMsg = "ELECTION ";

## byte[] cdAck = new byte[1024];

byte[] okAck = new byte[1024];
byte[] elAck = new byte[1024];
Runnable one, two, three, four;
Communication conObj;
String uname = "Node: " + curPid;
RingElection() throws Exception {
one = new RecvThread();
two = new SendThread();
three = new CRThread();
four = new CSThread();
conObj = new Communication();
StartProcess();
}
void StartProcess() {
DatagramPacket cdSend, cdRecv, cdSend2;
try {
byte[] cdsMsg = "ALIVE".getBytes();
byte[] cdrMsg = new byte[1024];
System.out.println("Node " + curPid + " Started");
while(true) {
cdRecv = new DatagramPacket(cdrMsg, cdrMsg.length);

if(curPid != coord) {
while(c_alive != 0) {
cdSend = new DatagramPacket(cdsMsg, cdsMsg.length,
socket1.send(cdSend);
try {
socket1.setSoTimeout(3000);
}
catch(Exception e) {
c_alive = 0; elNum = 0;
}
}

}
else if(curPid == coord) {
System.out.println("I'm the co-ordinator");
while(curPid == coord) {

cdSend2 = new DatagramPacket(cdsMsg, cdsMsg.length,
socket1.send(cdSend2);
}
}
}
}
catch(Exception e) {
}
}
class CRThread implements Runnable {

## public void run() {

try {
while(true) {
byte[] msg = new byte[1024];
byte[] kMsg = okMsg.getBytes();

int temp;

## DatagramPacket recvPacket = new DatagramPacket(msg, msg.length);

String str = new String(recvPacket.getData());

temp = Character.getNumericValue(str.charAt(0));
if(temp > coord) {
coord = temp;
cdPort = sPorts[coord-1];
System.out.println("Node " + coord + " restarted");
while(!queue.isEmpty())
queue.remove();
c_alive = 0;
elNum = 0;
}
}
}
catch(Exception e) {
}
}
}
class CSThread implements Runnable {

## public void run() {

try {
String str = Integer.toString(curPid);
byte[] elByte = str.getBytes();
while(true) {

## for(int i = 0; i < n; i++) {

if(i != curPid) {
DatagramPacket sendPacket = new DatagramPacket(elByte,
socket5.send(sendPacket);
}
}
}
}
catch(Exception e) {
System.out.println("ERROR in Server Check Send Thread");
}
}
}
class RecvThread implements Runnable {
public void run() {
try {
while(true) {
byte[] msg = new byte[1024];
byte[] kMsg = okMsg.getBytes();

## DatagramPacket recvPacket = new DatagramPacket(msg,

msg.length);
try {

DatagramPacket sendPacket = new DatagramPacket(kMsg,
String str = new String(recvPacket.getData());
str = str.trim();
String subStr = str.substring(0, 8);
int len = str.length();
System.out.println("Received : " + str);

if(subStr.equals("ELECTION")) {

socket2.send(sendPacket);
if(Character.getNumericValue(str.charAt(9)) != curPid) {
str = str + Integer.toString(curPid);
}
else {

## int[] nodes = new int[10];

int t = 0, grtNode = 0;
for(int i = 9; i < len; i++)
nodes[t++] = Character.getNumericValue(str.charAt(i));
for(int i = 0; i < t; i++) {
if(grtNode < nodes[i])
grtNode = nodes[i];
}

## String temp = cdMsg;

temp = temp + Integer.toString(grtNode);
coord = grtNode;
cdPort = sPorts[grtNode-1];
System.out.println("Co-Ordinator: Node " + grtNode);
c_alive = 1; elNum = 1;
}
}

if(subStr.equals("COORDNTR")) {
socket2.send(sendPacket);
if(Character.getNumericValue(str.charAt(9)) != curPid) {
coord = Character.getNumericValue(str.charAt(9));
cdPort = sPorts[coord-1];
System.out.println("Co-Ordinator: Node " + coord);
c_alive = 1; elNum = 1;
}
else {
coord = curPid;
cdPort = port1;
c_alive = 1; elNum = 1;
System.out.println("I'm the co-ordinator");
}
}
}
catch(Exception e) {
}
}
}
catch(Exception e) {
System.out.println("ERROR in thread 1" + e);
}

}
}
class SendThread implements Runnable {
public void run() {
try {
while(true) {
int live_node = 0;
byte[] msg = new byte[1024];
System.out.print("");
if(elNum == 0) {
elNum = 1;
String str = elMsg + Integer.toString(curPid);
byte[] elByte = str.getBytes();
for(int i = 0; i < n-1; i++) {
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
DatagramPacket sendPacket = new DatagramPacket(elByte,
socket3.send(sendPacket);
try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(3000);
String okAck = new String(recvPacket.getData());
System.out.println("Sent : " + str);
break;
}
catch(Exception e) {
}
}
}
while((!queue.isEmpty())) {

## String msStr = new String(queue.remove());

byte[] msByte = msStr.getBytes();
for(int i = 0; i < n-1; i++) {
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
DatagramPacket sendPacket = new DatagramPacket(msByte,
socket3.send(sendPacket);

try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(1000);
String okAck = new String(recvPacket.getData());
System.out.println("Sent : " + msStr);
break;
}
catch(Exception e) {
}
}
}
}
}
catch(Exception e) {
System.out.println("ERROR" + e);
}
}
}
class Communication extends JFrame implements ActionListener {
JTextArea taMessages;
JTextField tfInput;
JButton btnSend,btnExit;

## public Communication() throws Exception {

super(uname);
buildInterface();
}

## public void buildInterface() {

btnSend = new JButton("Send");
btnExit = new JButton("Exit");
taMessages = new JTextArea();
taMessages.setRows(10);
taMessages.setColumns(50);
taMessages.setEditable(false);
tfInput = new JTextField(50);
JScrollPane sp = new JScrollPane(taMessages,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JPanel bp = new JPanel( new FlowLayout());
setSize(500,300);
setVisible(true);
pack();
}

## public void actionPerformed(ActionEvent evt) {

if (evt.getSource() == btnExit ) {
System.exit(0);
}
else {

String str;
if((curPid == coord) && (queue.isEmpty())) {
for(int i = 0; i < n; i++) {
str = tfInput.getText(); //send
byte[] msg = str.getBytes();
if(i != curPid-1) {
try {
DatagramPacket sendPacket = new DatagramPacket(msg,
socket6.send(sendPacket);
}
catch(Exception e) {
}
}
str = "";
}
}
}
}

## public void run() {

String prev = "";

try {
while(true) {
if(curPid != coord) {
byte[] msg = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
String str = new String(recvPacket.getData());
str = str.trim();
if(str.equals(prev))
str = "Receiving same message";
else
prev = str;
str = "<Co-ordinator>: " + str;
str = "";
}
}
}
catch(Exception ex) {
}
}
}
}
public static void main(String args[]) throws Exception {
RingElection obj = new RingElection();
}
}

/**
* @author Benjamin Hill
*/
public class ClockSync {
/**
* The reason for this to exist. Use instead of
System.currentTimeMillis()
*/
public static long getAdjustedTime() {
return System.currentTimeMillis() + timerOffset;
}
/**
* Sends out a timestamped multicast "ping"
*/
@Override
public void run() {
ClockSync.this.bout.putShort(PACKET_CLASS);
ClockSync.this.bout.putInt(ClockSync.this.myId);
final DatagramPacket dp = new
DatagramPacket(ClockSync.this.bout.array(), ClockSync.this.bout.position(),
ClockSync.this.group, UPNP_MULTI_PORT);
try {
ClockSync.this.ms.send(dp);
ClockSync.this.bout.clear();
} catch (final IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.finer("Sent ClockSync ping");
}
}
/**
* Blocking thread for getting timer packets
*/
boolean running = false;
@Override
public void run() {
this.running = true;
while (this.running) {
try {
ClockSync.this.bin.clear();
final DatagramPacket dp = new
DatagramPacket(ClockSync.this.bin.array(), ClockSync.this.bin.capacity());
logger.finest("Waiting for next packet");
ClockSync.this.ms.receive(dp); // BLOCK HERE
ClockSync.this.bin.rewind();
final long now = ClockSync.getAdjustedTime();
final short pclass = ClockSync.this.bin.getShort();
if (PACKET_CLASS != pclass) {
logger.finest("Random packet, skipping");
continue;
}
final int id = ClockSync.this.bin.getInt();
if (id == ClockSync.this.myId) {
logger.finest("My own packet, skipping");
continue;
}
final long ts = ClockSync.this.bin.getLong();
if (now >= ts) {
logger.finest("Other peer is behind me, skipping");
continue;
}
logger.log(Level.FINER, "Got Relevent Packet:{0} {1} {2}", new
Object[]{pclass, id, ts});
final long ahead = ts - now;
timerOffset += (ahead >> 1);
logger.log(Level.INFO, "Other peer is {0} ahead of me, catching
up halfway with a new offset of {1}", new Object[]{ahead, timerOffset});
} catch (final IOException ex) {
logger.severe(ex.getLocalizedMessage());
this.running = false;
}
}
}
}
protected static volatile long timerOffset = 0;
static final Logger logger = Logger.getLogger(ClockSync.class.getName());
final static short PACKET_CLASS = 2700; // random
static final Random r = new Random();
static final String UPNP_ADDRESS = "239.255.255.250";
static final int UPNP_MULTI_PORT = 1900;
final ByteBuffer bin, bout;
final int BUFF_SIZE = Short.SIZE + Integer.SIZE + Long.SIZE; // Packet
class + machine ID + Time
final MulticastSocket ms;
final int myId;
public ClockSync() throws IOException {
this.ms = new MulticastSocket(null);
this.ms.setTimeToLive(4);
this.ms.setSoTimeout(0);
this.ms.setLoopbackMode(true);
logger.warning("MS Socket can't reuse address");
}
UPNP_MULTI_PORT));
this.ms.joinGroup(this.group);
this.bin = ByteBuffer.allocate(this.BUFF_SIZE);
this.bout = ByteBuffer.allocate(this.BUFF_SIZE);
this.myId = r.nextInt();
}
/**
* Don't forget to run this!
*/
public void startSync() {
}
/**
* Don't bother stopping it if you are ok with the overhead, in case new
clients join
*/
public void stopSync() {
this.rc.running = false;