Os Final Print Out

91
Ex.No:01 Date:18/02/10 SEMAPHORES - MULTIPROCESSOR OPERATING SYSTEMS Aim: To write a java program for implementing semaphores in multiprocessor OS. Algorithm: * Assume there are three processes: Pa, Pb, and Pc. Only Pa can output * the letter A, Pb B, and Pc C. * Utilizing only semaphores (and no other variables) the processes are * synchronized so that the output satisfies the following conditions: * a) A B must be output before any C's can be output. * b) B's and C's must alternate in the output string, that is, after the * first B is output, another B cannot be output until a C is output. * Similarly, once a C is output, another C cannot be output until a B * is output. * c) The total number of B's and C's which have been output at any given * point in the output string cannot exceed the number of A's which have 1

description

document

Transcript of Os Final Print Out

Ex.No:01Date:18/02/10SEMAPHORES - MULTIPROCESSOR OPERATING SYSTEMS

Aim:To write a java program for implementing semaphores in multiprocessor OS.

Algorithm:* Assume there are three processes: Pa, Pb, and Pc. Only Pa can output* the letter A, Pb B, and Pc C.* Utilizing only semaphores (and no other variables) the processes are* synchronized so that the output satisfies the following conditions:* a) A B must be output before any C's can be output.* b) B's and C's must alternate in the output string, that is, after the* first B is output, another B cannot be output until a C is output.* Similarly, once a C is output, another C cannot be output until a B* is output.* c) The total number of B's and C's which have been output at any given* point in the output string cannot exceed the number of A's which have* been output up to that point.* Examples* AACB -- invalid, violates a)* ABACAC -- invalid, violates b)* AABCABC -- invalid, violates c)* AABCAAABC -- valid* AAAABCBC -- valid* AB -- valid*/An Algorithm For More Than Two Processes:-/* Entry section for P1 */ /* Entry section for P2 */Q1 := True; Q2 := True;TURN := 1; TURN := 2;wait while Q2 and TURN := 1; wait while Q1 and TURN := 2;/* Exit section for P1 */ /* Exit section for P2 */Q1 := False; Q2 := False;

Both in this algorithm and in all of the previous ones, the processes busy-wait until they are allowed to enter the critical section. One might wonder why these algorithms busy-wait instead of simply context-switching to another ready process. At the beginning of this paper, we made the assumption that critical sections were usually very small; this would imply that any process busy-waiting on a lock would likely wait for a fairly short period of time. The overhead of context-switching is usually large enough that busy-waiting is more efficient. For critical sections that are longer, such as those with disk access, the above algorithms can be used as low-level building blocks for higher-level semaphores.

PROGRAM: -ABCs.javaimport java.io.Serializable;import java.util.Date;import java.util.Random;class BinarySemaphore {private boolean locked = false;BinarySemaphore() {} // constructorsBinarySemaphore(boolean initial) {locked = initial;}BinarySemaphore(int initial) {locked = (initial == 0);}public synchronized void P() {while (locked) {try {wait();} catch (InterruptedException e) {}}locked = true;}public synchronized void V(){if (locked) notify();locked = false;}}class CountingSemaphore {private int value = 0;private int waitCount = 0;private int notifyCount = 0;public CountingSemaphore(int initial){if (initial > 0) value = initial;}public synchronized void P() {if (value notifyCount) {notifyCount++;notify();}}}class Pa extends ABCs implements Runnable { // extend ABCs to// access semaphore sumpublic void run () {while (true) { nap(1+(int)(random(500)));System.out.print("A"); System.out.flush();try {V(sum);} catch (Exception e){}}}}class Pb extends ABCs implements Runnable {public void run () {while (true) { nap(1+(int)(random(800)));P(C); P(sum);System.out.print("B"); System.out.flush();V(B);}}}class Pc extends ABCs implements Runnable {public void run () {while (true) { nap(1+(int)(random(800)));P(B); P(sum);System.out.print("C"); System.out.flush();V(C);}}}class ABCs {protected static final BinarySemaphore B // these semaphores= new BinarySemaphore(0); // are staticprotected static final BinarySemaphore C // so subclasses= new BinarySemaphore(1); // Pa, Pb,protected static final CountingSemaphore sum // and Pc share= new CountingSemaphore(0); // themprivate static final long startTime = System.currentTimeMillis();protected static final long age() {return System.currentTimeMillis() - startTime;}private static final Random rnd = new Random();protected static final double random() {return rnd.nextDouble();}protected static final double random(int ub) {return rnd.nextDouble()*ub;}protected static final void P(BinarySemaphore s) { s.P(); }protected static final void V(BinarySemaphore s) { s.V(); }protected static final void P(CountingSemaphore s) { s.P(); }protected static final void V(CountingSemaphore s) { s.V(); }protected static final int nap(int napTimeMS) {long napStart = age();try {Thread.sleep(napTimeMS);} catch (InterruptedException e) {System.err.println("interrupted out of sleep");}return (int) (age() - napStart - (long) napTimeMS);}public static void main(String[] args) throws InterruptedException {Thread pa = new Thread(new Pa());Thread pb = new Thread(new Pb());Thread pc = new Thread(new Pc());pa.start(); pb.start(); pc.start();nap(9000);pa.stop(); pb.stop(); pc.stop();System.exit(0);} }

OUT PUT:-

Result:Thus the given program was coded and executed successfully.

Ex.No:02Date:25/02/10MULTITHREADING - MULTIPROCESSOR OPERATING SYSTEMS

Aim:To write a java program for solving the cigarette problem using multithreading.

Problem Description:-Consider a system with three smoker processes and one agent process. Each smoker continuously rolls a cigarette and then smokes it. But to roll and smoke a cigarette, the smoker needs three ingredients: tobacco, paper, and matches. One of the smoker processes has paper, another has tobacco, and the third has matches. The agent has an infinite supply of all three materials. The agent places two of the ingredients on the table. The smoker who has the remaining ingredient then makes and smokes a cigarette, signaling the agent on completion. The agent then puts out another two of the three ingredients, and the cycle repeats.

ALGORITHM:-The code for the agent process.1 do forever {2 P( lock );3 randNum = rand( 1, 3 ); // Pick a random number from 1-34 if ( randNum == 1 ) {5 // Put tobacco on table6 // Put paper on table7 V( smoker_match ); // Wake up smoker with match8 } else if ( randNum == 2 ) {9 // Put tobacco on table10 // Put match on table11 V( smoker_paper ); // Wake up smoker with paper12 } else {13 // Put match on table14 // Put paper on table15 V( smoker_tobacco ); } // Wake up smoker with tobacco16 V( lock );17 P( agent ); // Agent sleeps18 } // end forever loopThe code to one of the smokers. The others are analogous.1 do forever {2 P( smoker_tobacco ); // Sleep right away3 P( lock );4 // Pick up match5 // Pick up paper6 V( agent );7 V( lock );8 // Smoke (but don't inhale).9 }PROGRAM :-Agent.javaimport java.util.*;public class Agent extends Thread{private Table table;private Random rand;public Agent(Table tab,String name){super(name);table=tab;rand=new Random();}public void run(){while(true){switch(Math.abs(rand.nextInt())%3){case 0: table.put(Table.Tobacco_Paper);break;case 1: table.put(Table.Paper_Matches);break;case 2: table.put(Table.Matches_Tobacco);break;}}}}

Smoker .javaimport java.util.*;public class Smoker extends Thread{private Table table;private Random rand;private int needs;public Smoker(Table tab,String name,int what){super(name);table=tab;rand=new Random();needs=Table.Everything^what;}public void run(){while(true){try{table.get(needs);System.out.println(getName()+":Rolling.");sleep(Math.abs(rand.nextInt())%1000);System.out.println(getName()+":Smoking.");sleep(Math.abs(rand.nextInt())%1000);System.out.println(getName()+":Done Smoking.");table.DoneSmoking();}catch(InterruptedException e){}}}}Table.javaimport java.util.*;public class Table{public static final int Nothing=0;public static final int Tobacco=1;public static final int Paper=2;public static final int Matches=4;public static final int Tobacco_Paper=Tobacco+Paper;public static final int Paper_Matches=Paper+Matches;public static final int Matches_Tobacco=Matches+Tobacco;public static final int Everything=Tobacco+Paper+Matches;private int contains;public Table(){contains=Nothing;}public synchronized void put(int what){System.out.println(Thread.currentThread().getName()+":putting"+contains(what));contains=contains|what;notifyAll();try{wait();}catch(InterruptedException e){}}public synchronized void get(int what){while((contains&what)!=what){try{System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"-No!");wait();}catch(InterruptedException e){}}System.out.println(Thread.currentThread().getName()+":getting"+contains(what)+"-Yes!");contains=contains^what;}public synchronized void DoneSmoking(){notifyAll();}public String contains(int what){String s="";if((what&Tobacco)==Tobacco)s=s+"tobacco";if((what&Paper)==Paper)s=s+"paper";if((what&Matches)==Matches)s=s+"matches";return s;} }TableCS.javaimport java.util.*;public class TableCS extends Table{TableCS Table;}Cigarette.javaimport java.util.*;public class cigarette{public static void main(String[] args){Smoker smo1,smo2,smo3;Agent agent;Table table;table=new Table();agent=new Agent(table,"Agent");smo1=new Smoker(table,"Smoker 1",Table.Paper);smo2=new Smoker(table,"Smoker 2",Table.Matches);smo3=new Smoker(table,"Smoker 3",Table.Tobacco);agent.start();smo1.start();smo2.start();smo3.start();}}

OUTPUT:Smoker 2:Smoking.Smoker 2:Done Smoking.Smoker 2:gettingtobaccopaper-No!Smoker 3:gettingpapermatches-No!Smoker 1:gettingtobaccomatches-No!Agent:puttingtobaccomatchesSmoker 3:gettingpapermatches-No!Smoker 2:gettingtobaccopaper-No!Smoker 1:gettingtobaccomatches-Yes!Smoker 1:Rolling.Smoker 1:Smoking.Smoker 1:Done Smoking.Smoker 1:gettingtobaccomatches-No!Smoker 2:gettingtobaccopaper-No!Smoker 3:gettingpapermatches-No!Agent:puttingtobaccopaperSmoker 3:gettingpapermatches-No!Smoker 2:gettingtobaccopaper-Yes!Smoker 2:Rolling.Smoker 1:gettingtobaccomatches-No!Smoker 2:Smoking.Smoker 2:Done Smoking.Smoker 2:gettingtobaccopaper-No!Smoker 3:gettingpapermatches-No!Smoker 1:gettingtobaccomatches-No!Agent:puttingtobaccopaperSmoker 3:gettingpapermatches-No!Smoker 2:gettingtobaccopaper-Yes!Smoker 1:gettingtobaccomatches-No!Smoker 2:Rolling.Smoker 2:Smoking.Smoker 2:Done Smoking.Smoker 3:gettingpapermatches-No!Smoker 1:gettingtobaccomatches-No!Agent:puttingtobaccomatchesSmoker 2:gettingtobaccopaper-No!Smoker 3:gettingpapermatches-No!Smoker 1:gettingtobaccomatches-Yes!Smoker 1:Rolling.Smoker 1:Smoking.Smoker 1:Done Smoking.Smoker 3:gettingpapermatches-No!Smoker 2:gettingtobaccopaper-No!Smoker 1:gettingtobaccomatches-No!

Result:Thus the given program was coded and executed successfully.

Ex.No:03Date:04/03/10MULTIPLE SLEEPING BARBERS - MULTIPROCESSOR OPERATING SYSTEMS

Aim:Write a multi-class multithreaded Java program that simulates multiple sleeping barbers, all in one barbershop that has a finite number of chairs in the waiting room. Each customer is instantiated from a single Customer class, each barber is instantiated from a single Barber class.

PROBLEM DESCRIBTION:-

The Sleeping-Barber Problem. A barbershop consists of a waiting room with n chairs and the barber room containing the barber chair. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy but chairs are available,then the customer sits in one of the free chairs. If the barber is asleep, the customer wakes up the barber.

ALGORITHM:- The Barber (Thread/Process):while(true) { //runs in an infinite loopP(Customers) //tries to acquire a customer - if none is available he goes to sleepP(accessSeats) //at this time he has been awakened - want to modify the number of available seatsNumberOfFreeSeats++ //one chair gets freeV(Barber) //the barber is ready to cutV(accessSeats) //we don't need the lock on the chairs anymore//here the barber is cutting hair} The Customer (Thread/Process):while(true) { //runs in an infinite loopP(accessSeats) //tries to get access to the chairsif ( NumberOfFreeSeats > 0 ) { //if there are any free seatsNumberOfFreeSeats-- //sitting down on a chairV(Customers) //notify the barber, who's waiting that there is a customerV(accessSeats) //don't need to lock the chairs anymoreP(Barber) //now it's this customers turn, but wait if the barber is busy//here the customer is having his hair cut} else { //there are no free seats//tough luckV(accessSeats) //but don't forget to release the lock on the seats//customer leaves without a haircut}}

PROGRAM :Semaphore.java:class Semaphore extends Object{private int count;public Semaphore(int startingCount){count = startingCount;}public void down(){Synchronized (this) {while (count java WakeOnLan 172.15.169.8 00-15-58-A3-0C-27Wake-on-LAN packet sent.

Result:Thus the given program was coded and executed successfully.

Ex.No:05Date:26/03/10Real time operating systems

Aim:To write a real-time program implementing an alarm clock .

PROBLEM DESCRIPTION:-A clock with alarm functionality shall be implemented. It shall be possible to set the time. It shall be possible to set the alarm time. The alarm shall be enabled when the alarm time is set. The alarm shall be activated when the alarm is enabled, and when the current time is equal to the alarm time. An activated alarm must be acknowledged. Acknowledgement of an alarm shall lead to the alarm being disabled. The alarm is enabled again when a new alarm time is set. An alarm which is not acknowledged shall be repeated every 10 seconds. The program shall communicate with a graphical user interface, where the current time shall be displayed, and where the alarm time shall be displayed when the alarm is enabled. It shall be possible to terminate the program, using a command which is sent from the graphical user interface.

ALGORITHM:- Display init is used for initialization, and shall be called from the main function of the program, before the processes are created. Display time displays the current time, and shall be called by the clock process. Display alarm time shows the current alarm time, and shall be called when a new alarm time is set. Erase alarm time erases the displayed alarm time, and shall be called when the user acknowledges an alarm. Display alarm text is used to show an alarm activation, and shall be called when the user shall be informed that the alarm has been activated,i.e. when the alarm is activated the first time, and when the alarm is activated repeatedly (which is every 10 seconds, according to the above stated requirments). Erase alarm text erases the information displayed by display alarm text, and shall be called when the user acknowledges an alarm.

PROGRAM:-#include#include#includestruct clk{int hh,mm,ss;}c1,c2;void clock(int *h1,int *m1,int *s1){*s1=*s1+1;if(*s1==60){*s1=0; *m1=*m1+1;if(*m1==60){*m1=0;*h1=*h1+1;if(*h1==24)*h1=0;}}}void timer(int *h,int *m,int *s){if((*s)!=0){*s=*s-1;}else if((*s)==0){if(*m!=0){*s=59;*m=*m-1;}else if(*m==0){if(*h!=0){*m=59;*h=*h-1;}} }}void alarm(){int i;while(!kbhit()){for(i=0;i24||c2.mm>60||c2.ss>60){printf("\n\n\tERROR: Invalid time.\n\tRestart the program.");delay(2500);exit(0);}while((c1.ss!=c2.ss)||(c1.hh!=c2.hh)||(c1.mm!=c2.mm)){clrscr();printf("\n\nAlarm time: %02d:%02d:%02d\n",c2.hh,c2.mm,c2.ss);printf("\nCurrent Time: %02d:%02d:%02d",c1.hh,c1.mm,c1.ss);clock(&c1.hh,&c1.mm,&c1.ss);delay(1000);};clrscr();printf("\n\n\n\n\t\t\t\tAlarm time reached\n\n\t\t\t\tPress any to Exit.");alarm();exit(0);}break;case 'T':case 't':{printf("\n\n\nEnter time for timer (HH:MM:SS): ");scanf("%d:%d:%d",&c1.hh,&c1.mm,&c1.ss);while(c1.hh>0||c1.mm>0||c1.ss>0){clrscr();printf("The Current Time:\n");printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t");printf("%02d:%02d:%02d",c1.hh,c1.mm,c1.ss);timer(&c1.hh,&c1.mm,&c1.ss);delay(1000);}clrscr();printf("Program Written by: Anshu Krishna\n");printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\t");printf("00:00:00");alarm();exit(0);}break;default:{printf("\n\tInvalid Input\n\n\tPlease restart the program");delay(2500);exit(0);}} }

OUTPUT:

Result:Thus the given program was coded and executed successfully.

Ex.No:06Date:05/04/10Database operating systemsAssume any application(e.g.banking) on your own and do the following exercises.1. Investigate and implement the ObjectStore's concurrency options. The executions of transactions are all or none. The interleaving of multiple transactions is serializable. Update is atomic.

ALGORITHM:-

(i) Creation of bindings to the bank account object; (ii) Start of the application transaction; (iii) Method invocations; as a part of a given invocation the object will be locked in read or write mode; and (iv) Commit/abort of the transaction.2. Implement the concurrency conflict that occurs between multiple client applications. Reducing the preconditionsthat is, reducing the dependencies of the requestreduces the chance of optimistic failure. Reducing the chance of the preconditions being invalid reduces the chance of optimistic failure. Use postings and business actions to achieve the first. Try to change arbitrary data into either predictable reference data or into personal data to achieve the second.For predictable reference data we do not have to design for issues caused by concurrent change; we can just assume it will never happen, and that it is not worth the effort to design elaborate exception handling.For arbitrary data we have to design for exceptions caused by concurrent change. When we use arbitrary data, we accept the chance that we will have to tell the user that we encountered a concurrency issue. We accept that we will have to tell the user that the transaction was rejected, or that we have to ask the user for a resolution. We may have to design how to turn arbitrary data into predictable reference data, and also design for multiple validity periods of specific information, such as an address change.Arbitrary data may be problematic, and we should try to avoid using it as a precondition. That is, we should try to avoid using arbitrary data to formulate requests to the service, and avoid using it to support the users' decisions.For personal data we can accept exceptions, because they're easy to explain to the user, and should be expected. (The user caused them in the first place, for instance, by making offline changes on two systems.)Almost all recommendations in this article concern the design of the service interaction, and can thus be formulated as recommendations for good service design. Confine pessimistic resource usage I recommend using pessimistic concurrency behavior only in the confines of a system that is completely under control. That is, a system in which you control how long a user or process can lock or reserve resources. This reduces and controls the impact of resource use on other users. Limit optimistic updates I recommend limiting optimistic concurrency behavior to updates of master data with very limited side effects, and only for master data that does not change too oftenin other words, only for changes with a small or acceptable likelihood of running into an optimistic failure. Design business actions I recommend using business actions for formulating requests. By formulating the request and the prerequisites or assumptions, one can reduce the chance of conflict and make that chance explicit. Design postings I recommend using the pattern of postings as the preferred type of business action for communicating with services, to minimize the occurrence of optimistic failures. Use the journal pattern I recommend using what I call the journal pattern on top of postings and business actions. It is easy to explain to business managers, and it makes the design more reliable. It helps in making the requests uniquely identifiable, thus supporting an audit trail, and it helps in making the dependencies between business actions manageable. I recommend not changing the postings or business actions in the journal, but rather adding new "compensating" postings or business actions. The journal is part of the "data contract" of the service; the service publishes the schema of the journal. The journal can manage the dependencies between the posting requests it contains, it can document the audit trail, and its unique identification can prevent double postings. Reduce the dependency on arbitrary data Try making arbitrary data either: Predictable reference data by managing the time of validity. Personal data by assigning ownership (i.e. reducing the chance of concurrent updates).

3. Observe and implement the implication of nested transactions. Actions on unprotected objects.Protected actions which may be undone or redone.Real actions which may be deferred but not undone.Nested transactions which may be undone by invoking compensating transaction.

Nested transactions have several important features: When a program starts a new transaction, if it already inside of an existing transaction then a sub transaction is started otherwise a new top level transaction is started. There does not need to be a limit on the depth of transaction nesting. When a sub transaction aborts then all of its steps are undone, including any of its sub transactions. However, this does not cause the abort of the parent transaction; instead the parent transaction is simply notified of the abort. When a sub transaction is executing the entities that it is updating are not visible to other transactions or sub transactions (as per the isolation property). When a sub transaction commits then the updated entities are made visible to other transactions and sub transactions.

Program:CLIENT import java.io.*;import java.net.*;import java.util.*;import java.lang.*;public class client{public static void main(String args[]){try{Socket s=new Socket("172.15.169.3",8080);try{DataOutputStream out=new DataOutputStream(s.getOutputStream());DataInputStream in=new DataInputStream(s.getInputStream());out.writeInt(25);while(true){System.out.println("=========================================");System.out.println("1.Create a new Account");System.out.println("2.Check Balance");System.out.println("3.Withdraw");System.out.println("4.Deposit");System.out.println("5.Transfer");System.out.println("6.Exit");System.out.println("=========================================");Scanner sc=new Scanner(System.in);int choice;try{choice=sc.nextInt();}catch(Exception e){System.out.println("Enter the Correct Input");continue;}out.writeInt(choice);switch(choice){case 1:BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.print("Enter the Account Name:");String name=br.readLine();int acno1=0;boolean b1=false;try{System.out.print("Enter the Account Number:");acno1=sc.nextInt();b1=true;}catch(Exception e){System.out.println("Enter the Account Number Correctly");}out.writeBoolean(b1);if(b1== true){out.writeUTF(name);out.writeInt(acno1);}break;case 2:System.out.print("Enter the Account Number:");int acno=0;boolean pach=false;try{acno=sc.nextInt();}catch(Exception e){System.out.println("Enter the Valid Account Number");pach=true;}int bal=0;out.writeInt(acno);if(in.readBoolean()){bal=in.readInt();System.out.println("the Balance is:"+bal);}else{if(pach==false){System.out.println("Account not available");}}break;case 3:boolean check1=false;int acno3=0;int amt3=0;try{System.out.print("Enter the Account Number:");acno3=sc.nextInt();System.out.print("Enter the Ammount:");amt3=sc.nextInt();}catch(Exception e){System.out.println("Invalid Input");check1=true;}if(check1==false){out.writeInt(acno3);out.writeInt(amt3);if(in.readBoolean()){if(in.readBoolean()){System.out.println("Money is Withdrawn");}else{System.out.println("Money is not Enough to Withdraw");}}else{System.out.println("Account is not available");break;}}break;case 4:System.out.print("Enter the Account Number:");int acno4=sc.nextInt();out.writeInt(acno4);System.out.print("Enter the Ammount:");int amt4=sc.nextInt();out.writeInt(amt4);if(in.readBoolean()){System.out.println("Ammount is Deposited");}else{System.out.println("Check the Account Number");}break;case 5:System.out.print("Enter the From Account:");int tac1=sc.nextInt();out.writeInt(tac1);System.out.print("Enter the To Account:");int tac2=sc.nextInt();out.writeInt(tac2);System.out.print("Enter the Amount to transfer:");int tamt=sc.nextInt();out.writeInt(tamt);break;case 6:System.exit(0);break;default:System.out.println("Invalid Input");break;}}}finally{s.close();}}catch(IOException e){e.printStackTrace();}}}

SERVER import java.io.*;import java.net.*;import java.util.*;import java.sql.*;import java.lang.*;public class server{public static void main(String args[]){try{ServerSocket s=new ServerSocket(8080);while(true){Socket incoming=s.accept();Runnable r=new bankserver(incoming);Thread t=new Thread(r);t.start();}}catch(IOException e){e.printStackTrace();}}}class bankserver implements Runnable{private Socket incoming;public bankserver(Socket i){incoming=i;}public void run(){try{try{DataOutputStream out=new DataOutputStream(incoming.getOutputStream());DataInputStream in=new DataInputStream(incoming.getInputStream());System.out.println(in.readInt());while(true){int choice=in.readInt();System.out.println("You have selected choice"+choice);switch(choice){case 1:String name=null;int acno1=0;if(in.readBoolean()){name=in.readUTF();acno1=in.readInt();}else{break;}int a=0;try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:parthi");Statement st=con.createStatement();String str1="insert into parthi values('"+name+"','"+acno1+"','"+a+"')";st.executeUpdate(str1);}catch(Exception e){System.out.println("Account Number is already allocated");}break;case 2:int acno=in.readInt();try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:parthi");Statement st=con.createStatement();String s1="Select * from parthi where accnumber="+acno;System.out.println(s1);int bal=0;ResultSet rs=st.executeQuery(s1);boolean check=true;String name2=null;while(rs.next()){name2=rs.getString(1);bal=rs.getInt(3);}if(name2==null){check=false;out.writeBoolean(check);}else{out.writeBoolean(check);out.writeInt(bal);}}catch(Exception e){e.printStackTrace();}break;case 3:int acno3=in.readInt();int amt3=in.readInt();try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:parthi");Statement st=con.createStatement();String s1="Select * from parthi where accnumber="+acno3;System.out.println(s1);int bal=0;ResultSet rs=st.executeQuery(s1);String name3=null;boolean check3=true;while(rs.next()){bal=rs.getInt(3);name3=rs.getString(1);}if(name3== null){check3=false;}boolean chstatus=false;if(bal>0 && bal>amt3){Object lock2=new Object();synchronized(lock2){int tmp=bal-amt3;String s2="update parthi set balance="+tmp+" where accnumber="+acno3;System.out.println(s2);st.executeUpdate(s2);chstatus=true;}}else{System.out.println("Money not Ennough");}out.writeBoolean(check3);if(check3==true){out.writeBoolean(chstatus);}}catch(Exception e){e.printStackTrace();}break;case 4:int acno4=in.readInt();int amt4=in.readInt();System.out.println(acno4);System.out.println(amt4);try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:parthi");Statement st=con.createStatement();String s1="Select * from parthi where accnumber="+acno4;System.out.println(s1);String name1=null;ResultSet rs=st.executeQuery(s1);while(rs.next()){name1=rs.getString(1);}System.out.println(name1);boolean ch=false;if(name1!=null){System.out.println("hai");int actmp=0;ResultSet rs1=st.executeQuery(s1);while(rs1.next()){actmp=rs1.getInt(3);}System.out.println(actmp);Object lock1=new Object();synchronized(lock1){int tmpbal=actmp+amt4;String s2="update parthi set balance="+tmpbal+" where accnumber="+acno4;System.out.println(s2);st.executeUpdate(s2);}ch=true;out.writeBoolean(ch);}else{System.out.println("nO rECORD");out.writeBoolean(ch);}}catch(Exception e){e.printStackTrace();}break;case 5:int tac1=in.readInt();int tac2=in.readInt();int tamt=in.readInt();System.out.println(tac1+" "+tac2+" "+tamt);try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:parthi");Statement st=con.createStatement();String s1="Select * from parthi where accnumber="+tac1;String s2="Select * from parthi where accnumber="+tac2;System.out.println(s1);System.out.println(s2);ResultSet rs1=st.executeQuery(s1);int bal1=0;while(rs1.next()){bal1=rs1.getInt(3);}ResultSet rs2=st.executeQuery(s2);int bal2=0;while(rs2.next()){bal2=rs2.getInt(3);}if(bal1 < tamt){}else{Object lock=new Object();synchronized(lock){bal1=bal1-tamt;bal2=bal2+tamt;String s3="update parthi set balance="+bal1+" where accnumber="+tac1;String s4="update parthi set balance="+bal2+" where accnumber="+tac2;st.executeUpdate(s3);st.executeUpdate(s4);}}}catch(Exception e){e.printStackTrace();}break;case 6:System.out.println("Client is exit");break;default:System.out.println("Invalid Input from client");break;}}}catch(Exception e){System.out.println("Client is Disconnected");}finally{incoming.close();}}catch(IOException e){e.printStackTrace();}}}

OUTPUT :

Result:Thus the given program was coded and executed successfully.Ex.No:07Date:12/04/10

Distributed operating systems

Aim:To Design a RMI Lottery application.

Alorithm:Design a superimposed computation which detects that there exists an interleaving of underlying events in this system where at some state P ^Q holds. (A superposed computation is one that does not a_ect the underlying system; it may \read" but not \write" the state of the underlying system. Events in a superposed computation may occur in at the same instant as the underlying events and/or at di_erent instants.) State any assumptions you make.

Program:LottoMad.javaimport java.awt.*;import java.net.*;public class LottoMad1 extends java.applet.Appletimplements Runnable {Thread playing;// set up row 1Panel row1 = new Panel();CheckboxGroup option = new CheckboxGroup();Checkbox quickpick = new Checkbox("Quick Pick", option, false);Checkbox personal = new Checkbox("Personal",option, true);// set up row 2Panel row2 = new Panel();Label numbersLabel = new Label("Your picks: ", Label.RIGHT);TextField[] numbers = new TextField[6];Label winnersLabel = new Label("Winners: ", Label.RIGHT);TextField[] winners = new TextField[6];// set up row 3Panel row3 = new Panel();Button stop = new Button("Stop");Button play = new Button("Play");Button reset = new Button("Reset");// set up row 4Panel row4 = new Panel();Label got3Label = new Label("3 of 6: ", Label.RIGHT);TextField got3 = new TextField("0");Label got4Label = new Label("4 of 6: ", Label.RIGHT);TextField got4 = new TextField("0");Label got5Label = new Label("5 of 6: ", Label.RIGHT);TextField got5 = new TextField("0");Label got6Label = new Label("6 of 6: ", Label.RIGHT);TextField got6 = new TextField("0");Label drawingsLabel = new Label("Drawings: ", Label.RIGHT);TextField drawings = new TextField("0");Label yearsLabel = new Label("Years: ", Label.RIGHT);TextField years = new TextField("0");

public void init() {setBackground(Color.lightGray);GridLayout appletLayout = new GridLayout(5, 1, 10, 10);setLayout(appletLayout);FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10);row1.setLayout(layout1);row1.add(quickpick);row1.add(personal);add(row1);

GridLayout layout2 = new GridLayout(2, 7, 10, 10);row2.setLayout(layout2);row2.setLayout(layout2);row2.add(numbersLabel);for (int i = 0; i < 6; i++) {numbers[i] = new TextField();row2.add(numbers[i]);}row2.add(winnersLabel);for (int i = 0; i < 6; i++) {winners[i] = new TextField();winners[i].setEditable(false);row2.add(winners[i]);}add(row2);FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10, 10);row3.setLayout(layout3);stop.enable(false);reset.enable(false);row3.add(stop);row3.add(play);row3.add(reset);add(row3);

GridLayout layout4 = new GridLayout(2, 3, 20, 10);row4.setLayout(layout4);row4.add(got3Label);got3.setEditable(false);row4.add(got3);row4.add(got4Label);got4.setEditable(false);row4.add(got4);row4.add(got5Label);got5.setEditable(false);row4.add(got5);row4.add(got6Label);got6.setEditable(false);row4.add(got6);row4.add(drawingsLabel);drawings.setEditable(false);row4.add(drawings);row4.add(yearsLabel);years.setEditable(false);row4.add(years);add(row4);}

public boolean action(Event event, Object object) {if (event.target instanceof Button) {if (event.target.equals(reset)) {clearAllFields();reset.enable(false);play.enable(true);quickpick.enable(true);personal.enable(true);for (int i = 0; i < 6; i++) {numbers[i].setEditable(true);}}if (event.target.equals(play)) {playing = new Thread(this);play.enable(false);stop.enable(true);reset.enable(false);quickpick.enable(false);personal.enable(false);playing.start();}if (event.target.equals(stop)) {stop.enable(false);reset.enable(true);quickpick.enable(false);personal.enable(false);for (int i = 0; i < 6; i++) {numbers[i].setEditable(false);}playing.stop();playing = null;}}if (event.target instanceof Checkbox) {if (event.target.equals(quickpick)) {for (int i = 0; i < 6; i++) {int pick;do {pick = (int)Math.floor(Math.random() * 50 + 1);} while (numberGone(pick, numbers, i));numbers[i].setText("" + pick);}} else {for (int i = 0; i < 6; i++)numbers[i].setText(" ");}}return true;}

void clearAllFields() {for (int i = 0; i < 6; i++) {numbers[i].setText("");winners[i].setText("");}got3.setText("0");got4.setText("0");got5.setText("0");got6.setText("0");drawings.setText("0");years.setText("0");}

void addOneToField(TextField field) {int num = Integer.parseInt(field.getText());num++;field.setText("" + num);}public void stop() {stop.enable(false);reset.enable(false);play.enable(true);quickpick.enable(true);personal.enable(true);playing.stop();playing = null;clearAllFields();}boolean numberGone(int num, TextField[] pastNums, int count) {for (int i = 0; i < count; i++)if (Integer.parseInt(pastNums[i].getText()) == num)return true;return false;}

boolean matchedOne(TextField win, TextField[] allPicks) {for (int i = 0; i < 6; i++) {String winText = win.getText();if ( winText.equals( allPicks[i].getText() ) )return true;}return false;}public void run() {while (true) {addOneToField(drawings);int draw = Integer.parseInt(drawings.getText());float numYears = (float)draw / 104;years.setText("" + numYears);

int matches = 0;for (int i = 0; i < 6; i++) {int ball;do {ball = (int)Math.floor(Math.random() * 50 + 1);} while (numberGone(ball, winners, i));winners[i].setText("" + ball);if (matchedOne(winners[i], numbers))matches++;}switch (matches) {case 3:addOneToField(got3);break;case 4:addOneToField(got4);break;case 5:addOneToField(got5);break;case 6:addOneToField(got6);stop.enable(false);play.enable(true);reset.enable(true);playing.stop();}try { Thread.sleep(100); }catch (InterruptedException e) {}}}}

OUTPUT

Result:Thus the given program was coded and executed successfully.47