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 */
link(proc[i], proc[i+SQPROCS]);
link(proc[i+SQPROCS], proc[i]);
}
if (i%SQPROCS<SQPROCS-1) { /* link horizontally */
link(proc[i], proc[i+1]);
link(proc[i+1], proc[i]);
}
}
}

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<clientThread> t;
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();
clientThread th=new clientThread(ser,clientSocket);
(ser.t).add(th);
System.out.println("\nNow Total clients are : "+(ser.t).size());
(ser.data).add("NOT_SENT");
th.start();
}
catch (IOException e)
{
}
}

try
{
serverSocket.close();
}
catch(Exception e1)
{
}
}
}
class clientThread extends Thread
{
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());
os.println("Enter your name.");
name = is.readLine();
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)
{
line = is.readLine();
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);
inputLine = new BufferedReader(new InputStreamReader(System.in));

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
{
new Thread(new Client()).start();
while (!closed)
{
os.println(inputLine.readLine());
}
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;
Thread thread1, thread2, thread3, thread4;
Communication conObj;
String uname = "Node: " + curPid;
RingElection() throws Exception {
one = new RecvThread();
two = new SendThread();
three = new CRThread();
four = new CSThread();
thread1 = new Thread(one);
thread2 = new Thread(two);
thread3 = new Thread(three);
thread4 = new Thread(four);
thread2.start();
thread1.start();
thread4.start();
thread3.start();
conObj = new Communication();
StartProcess();
Thread.currentThread().sleep(3000);
}
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,
InetAddress.getByName(cdAddress), cdPort);
socket1.send(cdSend);
try {
socket1.setSoTimeout(3000);
socket1.receive(cdRecv);
}
catch(Exception e) {
c_alive = 0; elNum = 0;
}
}

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

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

public void run() {

System.out.println("Receive thread started");


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

int temp;

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

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

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

public void run() {


System.out.println("Send Thread started");
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,
elByte.length, InetAddress.getByName(sAddress[i]), cPorts[i]);
Thread.currentThread().sleep(250);
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();
Thread.currentThread().sleep(6000);

DatagramPacket recvPacket = new DatagramPacket(msg,


msg.length);
try {

socket2.receive(recvPacket);
DatagramPacket sendPacket = new DatagramPacket(kMsg,
kMsg.length, recvPacket.getAddress(), recvPacket.getPort());
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);
queue.add(str);
}
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];
cdAddress = address[grtNode-1];
System.out.println("Co-Ordinator: Node " + grtNode);
c_alive = 1; elNum = 1;
queue.add(temp);
}
}

if(subStr.equals("COORDNTR")) {
socket2.send(sendPacket);
if(Character.getNumericValue(str.charAt(9)) != curPid) {
coord = Character.getNumericValue(str.charAt(9));
cdPort = sPorts[coord-1];
cdAddress = address[coord-1];
System.out.println("Co-Ordinator: Node " + coord);
c_alive = 1; elNum = 1;
queue.add(str);
}
else {
coord = curPid;
cdPort = port1;
cdAddress = address1;
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];
Thread.currentThread().sleep(3000);
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,
elByte.length, InetAddress.getByName(address[i]), port[i]);
socket3.send(sendPacket);
try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(3000);
socket3.receive(recvPacket);
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,
msByte.length, InetAddress.getByName(address[i]), port[i]);
socket3.send(sendPacket);

try {
live_node = (curPid % n) + i + 1;
socket3.setSoTimeout(1000);
socket3.receive(recvPacket);
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();
new MessagesThread().start();
}

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);
add(sp,"Center");
JPanel bp = new JPanel( new FlowLayout());
bp.add(tfInput);
bp.add(btnSend);
bp.add(btnExit);
add(bp,"South");
btnSend.addActionListener(this);
btnExit.addActionListener(this);
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,
msg.length, InetAddress.getByName(sAddress[i]), mPorts[i]);
socket6.send(sendPacket);
}
catch(Exception e) {
}
}
str = "";
}
}
}
}

class MessagesThread extends Thread {

public void run() {


String prev = "";

try {
while(true) {
if(curPid != coord) {
byte[] msg = new byte[1024];
DatagramPacket recvPacket = new DatagramPacket(msg,
msg.length);
socket6.receive(recvPacket);
String str = new String(recvPacket.getData());
str = str.trim();
if(str.equals(prev))
str = "Receiving same message";
else
prev = str;
str = "<Co-ordinator>: " + str;
taMessages.append(str + "\n");//receive
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"
*/
final class BroadcastTask extends TimerTask {
@Override
public void run() {
ClockSync.this.bout.putShort(PACKET_CLASS);
ClockSync.this.bout.putInt(ClockSync.this.myId);
ClockSync.this.bout.putLong(ClockSync.getAdjustedTime());
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
*/
final class ReceiveThread implements Runnable {
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 InetAddress group;
final MulticastSocket ms;
final int myId;
final ReceiveThread rc = new ReceiveThread();
final Thread recThread = new Thread(rc);
final Timer broadTask = new Timer();
public ClockSync() throws IOException {
this.ms = new MulticastSocket(null);
this.group = InetAddress.getByName(UPNP_ADDRESS);
this.ms.setTimeToLive(4);
this.ms.setSoTimeout(0);
this.ms.setLoopbackMode(true);
this.ms.setReuseAddress(true);
if (!this.ms.getReuseAddress()) {
logger.warning("MS Socket can't reuse address");
}
this.ms.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"),
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() {
this.recThread.start();
this.broadTask.schedule(new BroadcastTask(), 0, 5000);
}
/**
* Don't bother stopping it if you are ok with the overhead, in case new
clients join
*/
public void stopSync() {
this.rc.running = false;
this.broadTask.cancel();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (!this.ms.isClosed()) {
if (this.ms.isBound() && !this.ms.isClosed()) {
this.ms.leaveGroup(this.group);
this.ms.close();
}
}
}
}