Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Module Title and Code: CE00361-3 Computing and Concurrent System Design
Date Assigned:
CCSD
TABLE OF CONTENTS
1 2
PROBLEM .............................................................................................................................. 5 REQUIREMENTS .................................................................................................................. 6 2.1 2.2 BASIC REQUIREMENTS .............................................................................................. 6 ADDITIONAL REQUIREMENTS ................................................................................. 8
3 4 5 6
ASSUMPTIONS ................................................................................................................... 10 SOLUTION........................................................................................................................... 11 STRUCTURE DIAGRAM ................................................................................................... 12 CODING TECHNIQUES ..................................................................................................... 13 6.1 OBJECT-ORIENTED CONCEPTS .............................................................................. 13 INHERITANCE ...................................................................................................... 13 OVERRIDING ........................................................................................................ 14 POLYMORPHISM ................................................................................................. 15 ENCAPSULATION ............................................................................................... 17 INTERFACES ........................................................................................................ 17 PACKAGES ........................................................................................................... 18 STATIC KEYWORD ............................................................................................. 20
Asia Pacific Institute of Information technology 7.2 7.3 7.4 7.5 7.6 8
CCSD
PAUSE EXECUTION WITH SLEEP ........................................................................... 26 SYNCHRONIZED METHODS .................................................................................... 26 GUARDED BLOCKS.................................................................................................... 27 WAIT() ........................................................................................................................... 28 NOTIFYALL() ............................................................................................................... 29
CONCURRENT PROGRAMMING DESING .................................................................... 30 8.1 8.2 FINITE STATE PROCESS (FSP) ................................................................................. 30 LABEL TRANSITION SYSTEMS (LTS) .................................................................... 34 ASSISTANT ........................................................................................................... 34 LANDLORD........................................................................................................... 34 CLOCK ................................................................................................................... 35 CUSTOMER ........................................................................................................... 35 BARMAID .............................................................................................................. 36 ORDERQUEUE ..................................................................................................... 36
SOURCE CODE LISTING .................................................................................................. 37 TESTING .............................................................................................................................. 46 SAMPLE OUTPUT .............................................................................................................. 48 CUSTOMER ....................................................................................................................... 48 TABLES ............................................................................................................................... 50 INGREDIENTS................................................................................................................... 51 CONTAINERS .................................................................................................................... 52 ORDERQUEUE .................................................................................................................. 52 ASSISTANT ........................................................................................................................ 53 LANDLORD........................................................................................................................ 53
12
CCSD
CCSD
LIST OF FIGURES
5-1: Structure Diagram ................................................................................................................. 12 6-1: Package structure ................................................................................................................... 19 8-1 : LTS for Assistant .................................................................................................................. 34 8-2 : LTS for Landlord .................................................................................................................. 34 8-3: LTS for Clock ........................................................................................................................ 35 8-4 : LTS for Customer ................................................................................................................. 35 8-5 : LTS for Barmaid................................................................................................................... 36 8-6 : LTS for OrderQueue............................................................................................................. 36
CCSD
1 PROBLEM
Intention of this assignment is to develop a simulation application to represent the processes of a bar. All business operations during the bar runtime must be included in the simulation. Graphical representation of events is not needed, but textual output is expected describing the events taking place. At the end of the simulation statistical data related to operations performed has to be displayed.
CCSD
2 REQUIREMENTS
2.1 BASIC REQUIREMENTS
1. The bar consists of tables, a serving area, a cupboard, a clock, a landlord, a barmaid, an assistant and a number of customers waiting in a queue. 2. Landlord and barmaid make and serve drinks to customers who order at the Bar in a firstcome-first-served manner 3. Each customer may only order a single drink at one time. The Landlord and Barmaid can each serve only a single customer at a time, although others may be waiting to be served. 4. There is one order queue to both the Landlord and The Barmaid. 5. On receipt of an order, the Landlord or the Barmaid will refuse to serve a drink for any customer ordering after closing time 6. If it is not closing time, the Landlord and Barmaid serve customers independently. They serve fruit juice, cappuccino, or hot chocolate, according to what the customers order. After having received an order they go to the cupboard and take out a glass or a cup, according to the type of drink ordered. If none are available, the Landlord or Barmaid will wait at the cupboard for a glass or cup to be placed back in the cupboard by the Assistant. 7. Fruit juice: Obtain a glass, obtain the juice fountain tap, fill the glass 8. Cappuccino: Obtain a cup , obtain each ingredients coffee and milk, mix the drink 9. Hot chocolate: Obtain a cup , obtain each ingredients choco powder and milk, mix the drink 10. After making the drinks the ingredients are returned to the cupboard. 11. The Barmaid leaves at closing time. The Landlord will not leave the restaurant until all others (customers, Assistant, Barmaid) have left the restaurant. 12. At ten-minutes before closing time the Landlord calls "last orders" to warn the customers that closing time is soon. The Landlord will be alerted by the Clock of this. The Landlord may finish serving any customers order he started before attending to the last orders call. 13. The serving area consists of a fruit juice tap and a cupboard. The cupboard contains all the ingredients, and the cups and glasses. 6
Asia Pacific Institute of Information technology 14. There are a limited number of glasses and cups in the system.
CCSD
15. Each of the ingredients (coffee, choco powder and milk) and the fruit juice tap are separate resources. Each of these resources may only be used by one person at a time. 16. To serve a customer the Landlord or the Barmaid takes one glass or cup, collects all the ingredients they need one at the time, makes and pours the drink, puts the ingredients back and finally serves the customer. 17. The customers enter the Restaurant at regular time intervals spread throughout the lifetime of the simulation. 18. On entering the Restaurant, each customer will order a drink, which will be served by either the Landlord or the barmaid and will then move to a favourite table. 19. Each customer orders only one type of drink. The type of drink ordered is determined at random according to the set ratio. 20. Standing, they will drink the contents of their drink in a set time and then try to put the empty glass/cup down on the table. 21. If the table is full when a customer wants to put the glass down, the customer will have to wait for the table to be cleared by the Assistant before putting the glass down. 22. Having placed the glass on the table, the customer may then 23. go back to the bar to order another drink until the customer has either drunk the set number of drinks 24. Or the Landlord refuses to give a drink because it is closing time. In either case, the customer will leave the restaurant straight away. 25. Some of the juice-drinking customers exhibit the following additional behavior: when they hear the landlord call "last orders", if they are not currently drinking the last of their set number of drinks, they will finish their current fruit-juice instantly and go to the bar to order one and only one more. 26. There are a number of tables in the bar that the customer use to put down their glasses and cups after finishing their drink. 27. The tables have a limited number of units of space for cups and glasses. A cup takes up two units of space on the table; a glass takes up one unit. 28. There is no bound on the number of customers around any table. A customer never puts down his drink on a table unless it is finished. 7
CCSD
29. It must be possible to fill a table. If there is only one free unit of space left on the table and a customer wants to put down a cup he may not block a second customer being able to put down his glass. 30. Tables mind their own business: tables should be independent of each other. For instance, a delay in one table should not affect the other ones. 31. The Assistant has the job of clearing the glasses and cups away from each table in turn, washing them and placing them back in the cupboard once they are all washed. 32. It is assumed that the Assistant is able to transport as many glasses as necessary on each clearing-up round. Any glasses on a table are assumed to be empty - the Assistant does not check the glasses to see if they are empty before collecting them. 33. There is a set period of time allowed for the collection of each glass/cup, washing of each glass/cup, and replacement of each glass/cup in the cupboard. 34. After each collect-wash-replace cycle the Assistant is allowed a rest period before commencing another cycle. 35. The assistant continues this operation after closing time is reached, making his final round once all customers have left.
Check that the number of cups and glasses in the cupboard is the same as the initial number of cups and glasses. Check that all tables are indeed empty. Print out statistics on
o
CCSD
Number of tables. Initial number of glasses/cups. Time to fetch/replace a glass/cup. Time to fetch the different ingredients. Capacity of table. Time to put down/pick up a glass or a cup. Time to make chocolate/cappuccino or pour fruit-juice. Time to wash a glass/cup. Waiting time between washing rounds. Number of customers entering the bar. It should be possible to set this to zero. The ratio of different types of drinkers, cappuccino, chocolate and, fruit-juice (both those who take one more when they hear last orders, and those who don't). It should be possible to set a drinking type to zero.
o o
CCSD
3 ASSUMPTIONS
1. No of customers entering bar is 5, and the gap between two arrivals is 30milliseconds 2. restaurant runs for 30000 milliseconds, and last orders is called on final 5000 milliseconds 3. Unlimited amounts of ingredients are available 4. All tables have same number of space. 5. The number of cups and glasses in the bar is 6 6. The maximum no of drinks per customer is limited to 2 to make the simulation more realistic. 7. There are 4 tables with 4 spaces each 8. maximum number of orders for a single customer is 2 (to make the simulation easy to understand)
10
CCSD
4 SOLUTION
The solution is to develop the simulation for the bar using concurrency and object oriented concepts of Java language. (Language specified in requirements). The designing of the solution is described in the following chapters.
11
CCSD
5 STRUCTURE DIAGRAM
stopQueue
Serving Area
getCustomer getOrder
prepare
Barmaid
leave
work
Cupboard
getIngredients getContainer
prepare
Landlord
closeBar work
update
OrderQueue
Dining Area
lastRound
Assistant
clean
clean
Notify Observers
Clock
12
CCSD
6 CODING TECHNIQUES
6.1 OBJECT-ORIENTED CONCEPTS
Since Java heavily supports object oriented programming concepts, this application also uses them throughout the implementation.
6.1.1 INHERITANCE
Used when one object acquires properties of another object. With inheritance this information is managed in a hierarchical manner. "extends"
public class Ingredients {} public class ChocoPowder extends Ingredients {} public class Coffee extends Ingredients {} public class FruitJuiceFountain extends Ingredients {}
With this extending the subclasses will inherit all the protected and public attributes and methods of superclass. Therefore, this implies that the subclass is a type of superclass. E.g. : ChocoPowder is a type of Ingredient "implements"
public interface DrinksInterface {} public class Cappucino implements DrinksInterface {}
13
CCSD
This is used for classes that inherit from a interface. Interfaces cannot be extended, and therefore are implemented. Here, the interface DrinksInterface is the superclass for subclassesCapuccino,FruitJuice and HotChocolate.
6.1.2 OVERRIDING
When a class inherits from a superclass, there is a chance that it overrides the functionality in superclass. Overriding definitely occurs when the superclass is an interface and might occur when extending happens. E.g. :
"extend"
The write method of Coffee class which extends from Ingredients class is overridden.(note the annotation)
@Override public void write(String msg, ServersInterface s) {}
"implements"
In HotChocolate class which implements from DrinksInterface overrides all the methods in the interface. HotChocolate class:
@Override public String getDrinkName() {} @Override public void prepare(Customer c) {} @Override
14
CCSD
DrinksInterface interface:
public String getDrinkName(); public void prepare(Customer c); public void write(String msg, Customer c); public void drink(Customer c); public ContainersInterface getContainer();
The reason for overriding is that not always the superclass can provide services. Sometimes, the service will have to be customized to suite the concrete class. This is the case in "extend" because some implementation does exist in superclass. But in "implement", the methods has to be overridden to provide implementation because interface does not provide any.
6.1.3 POLYMORPHISM
Polymorphism is the ability of an object to take multiple forms. Mostly this occurs when a super class reference is used to refer to a sub class reference E.g.: Drinks class:
Cappucino c = new Cappucino();
15
CCSD
public synchronized void prepare(Customer customer) { if (customer.getDrink() instanceof Cappucino) { c.prepare(customer); } else if (customer.getDrink() instanceof HotChocolate) { h.prepare(customer); } else if (customer.getDrink() instanceof FruitJuice) { f.prepare(customer); } else { write(); } notifyAll(); }
Customer class:
public DrinksInterface getDrink() { return drink; }
This method prepare(Customer customer) is responsible for preparing a drink. The server (landlord or barmaid) calls this method to access the relevant prepare method of concrete classes that implements DrinksInterface. (Drink class also implements DrinkInterface interface). Notice that in Customer class, the getDrink() method returns a DrinkInterface. This output is checked against concrete drinks classes to check to which concrete class this drink belongs to, using
instanceof
CCSD
6.1.4 ENCAPSULATION
Encapsulation is to make fields in a class private and provide access to them via public methods. This is therefore considered as a data hiding mechanism. The mutator and accessor methods are the public methods that transfer these private data fields. E.g.: Customer class:
private int tableIndex = -1; private int tableUnits = -1;
6.1.5 INTERFACES
Interfaces are a collection of abstract methods. When a class implements an interface, it inherits the abstract methods in the interface. An advantage over abstract classes is that, a single class can implement multiple interfaces where as only one extending is possible. 17
CCSD
Notice that both these classes have implemented the Runnable method as well. Therefore multiple inheritance from interfaces has happened. This multiple inheritance would not be possible of they were abstract or normal classes that needs extending. Therefore, this is the reason for using interfaces over abstract classes(although extending has not happened here)
6.1.6 PACKAGES
A package is a grouping of related types (classes, interfaces, etc) to provide access protection. Following is the package structure for this application.
18
CCSD
The classes relating are enclosed in a single package. As in the above diagram, all the classes related to ingredients is kept in a package called Ingredients. The classes also uses existing packages in Java to access the source codes. E.g. : Landlord class :
// The package Landlord class belongs to package People; // Importing existing Java packages import java.util.Observable; import java.util.Observer; // Importing custom packages import Containers.Containers; import Drinks.Drinks;
19
CCSD
The number of cups in the shelf is a fixed number and is not for objects, its for the class.
20
CCSD
6.2.1 SINGLETON
Singleton pattern was used when only one instance of a class was needed. This was applied for the
People Barmaid, Landlord, Assistant, OrderQueue Resources Ingredients ( the concrete ingredients Milk, Coffee, ChocoPowder, FruitJuiceFountain), Clock, CupManager, GlassManager,TableManager.
6.2.2 STRATEGY
The complete strategy pattern was not implemented. But the concept of accessing a method in a different class as the method in one class was used. E.g.: Drink class :
public synchronized void prepare(Customer customer) { if (customer.getDrink() instanceof Cappucino) { c.prepare(customer);
21
CCSD
The drink class's prepare method, calls the prepare methods of appropriate Drink classes (Cappucino,HotChocolate or FruiJuice).
6.2.3 OBSERVER
This pattern was used to inform the landlord of the time. The clock extends the java Observable interface and the landlord attaches himself to the clock as an observer. When last 10 minutes arrives, the clock notifies its observers, the landlord, who calls last orders. Similar process happens for closing time Clock class :
public class Clock extends Observable implements Runnable { public void notifyPeople(int time) { setChanged(); notifyObservers(time); }
22
CCSD
Landlord Class :
public class Landlord implements ServersInterface, Runnable, Observer { private Clock clock = Clock.getInstance(); private Landlord() { clock.addObserver(this); };
public void update(Observable o, Object arg) { if (Integer.parseInt(arg.toString()) == 10) { write("LAST ORDER>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); } else { write("CLOSING TIME>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); closeBar(); } Barmaid.getInstance().leave(); } }
23
CCSD
24
CCSD
7.1 THREADS
Creating a thread is the base for concurrency. By creating threads for the objects in the application they can be executed concurrently. Concurrency is the whole intention of the simulation. Main thread is the thread which runs the program and is resulted in the execution of,
public static void main(String args[]) {}
method. Here we need to make the objects in the simulation operate parallel. Therefore, for those objects, the Threads concept was implemented. To create the instance of Thread, the Runnable interface was implemented. This was the method used throughout the application. E.g. :
public class OrderQueue implements Runnable {}
Implementing this method will require overriding of the run() method, which will be the method that starts executing when the thread of that object starts.
public void run() {}
When the thread needs to start execution the following code segment
Clock clk = Clock.getInstance(); Thread t = new Thread(clk); t.setName("Thread-Clock"); t.start();
25
CCSD
(Note : only the relevant code to demonstrate sleep method is listed) The above thread sleeps for 1000 milliseconds before going to the next loop.
CCSD
one thread is accessing the synchronized method, it will not allow another thread to access the same method. All the other threads who request access to that method will be suspended of execution. The classes ServingArea and DiningArea, uses most synchronized methods throughout the application. The use of synchronizing is essential when a shared resource exists for multiple threads. In the ServingArea class which handles the ordering process, the methods are accessed by customers, barmaid and landlord, which will be 2 or more threads at any given time. Therefore synchronization is used. E.g. : ServingArea class has the following synchronized methods
public synchronized void getCustomer(ServersInterface s) {} public synchronized void getOrder(ServersInterface s) {} public synchronized void setNewCustomer(Customer c) {} public synchronized void makeOrder(Customer c) {} public synchronized void serveCustomer(Customer c) { }
27
CCSD
The objects that access this method are barmaid and landlord. They call this method when they want a customer to serve. The newArrival boolean means whether a new customer has arrived or not. Therefore when either barmaid or landlord accesses this thread, they stay inside the while loop until newArrival boolean value becomes true. Then, they move to the executions that follows the while loop.
7.5 WAIT()
This wait() method is extended from the object class along with other methods notify() and
notifyAll()
that will be discussed later. This causes the current thread to wait until another
thread invokes either notify() or notifyAll() method for this object which wakes up the thread. This immensely reduces the number of loops that needs to be executed specified in guarded blocks. The wait() method releases the object key. As soon as it is woken it checks for the guarded condition and secures the key. E.g. : ServingArea class
public synchronized void getOrder(ServersInterface s) { Customer c = s.getCustomer(); while (!c.getOrdered()) { try { s.write("waiting for customer to order"); wait(); } catch (InterruptedException e) {
28
CCSD
The thread comes into the method and checks the condition and waits inside the while loop if
c.getOrdered()
the condition. At the point where the condition c.getOrdered() becomes true, it exits from the
while
loop and continues execution. In concise, a thread waits on an objects monitor by calling
7.6 NOTIFYALL()
The notifyAll() method wakes up all the threads waiting on this objects monitor. When a thread is awakened, still it cannot proceed until the key is released. The awakened threads will compete with the other threads that might also be waiting to secure the object's key. There is no guarantee as to which thread will acquire the key. But who ever acquires the key will go through their guarded blocks to see whether they can continue executing and works accordingly.
notify()
method wakes up a single thread and we do not know which thread will wake up.
However, notify() method is not used in this application. Only notifyAll() is used. E.g. : ServingArea class
public synchronized void makeOrder(Customer c) { c.write(c.getDetails() + " is making the order and waiting"); c.setOrdered(true); notifyAll(); }
29
CCSD
Notice that, the c.setOrdered(true) method sets a boolean value to true. There might be a synchronized method on which a thread is waiting having made that boolean condition its guarded block. Therefore, when notifyAll() method wakes up all the threads in the objects monitor, that particular thread will have a chance to continue its execution by exiting its guarded block while loop.
30
CCSD
ORDERLL
(getContainer->getIngredients->prepareDrink->returnIngredients-
>serve->LANDLORD).
CLOCK = (tick[i:TIMES]-> if(i==0) then //bar open (open->CLOCK) else if(i==1) then (lastOrder->CLOCK) else
31
CCSD
CUSTOMER = (close[i:CLOSE]-> if(i==0) then //bar open (moveToEnd->moveToFront->order->SERVE) else //bar closed (stop->CUSTOMER)), SERVE = (serve->removeFromQueue->goToTable->drink->lastDrink[j:LASTDRINK]-> if(j==0) then//not the last drink, order again (lastOrder[k:LASTORDERS]-> if(k==0) then//last orders not called (putdownContainer->CUSTOMER)//order again else//last orders called (putdownContainer->leave->CUSTOMER))//either leaves or orders the last drink else//is the last drink (putdownContainer->leave->CUSTOMER)).
32
CCSD
(getContainer->getIngredients->prepareDrink->returnIngredients-
>serve->BARMAID).
ORDERQUEUE = (close[i:CLOSE]-> if(i==0) then //bar open (createCustomer->moveToEnd->moveToFront-> removeFromQueue->ORDERQUEUE) else //bar closed (stop->ORDERQUEUE) ).
||ORDERQUEUE_CUSTOMER = (ORDERQUEUE||CUSTOMER). ||ORDERQUEUE_CUSTOMER_BARMAID = (ORDERQUEUE_CUSTOMER||BARMAID). ||LANDLORD_CLOCK = (LANDLORD||CLOCK). ||ORDERQUEUE_CUSTOMER_BARMAID_LANDLORD_CLOCK (ORDERQUEUE_CUSTOMER_BARMAID||LANDLORD_CLOCK ). ||ORDERQUEUE_CUSTOMER_BARMAID_LANDLORD_CLOCK_ASSISTANT (ORDERQUEUE_CUSTOMER_BARMAID_LANDLORD_CLOCK ||ASSISTANT ). = =
33
CCSD
close.0 clean
clean
getContainers washContainers
washContainers returnContainers
close.0 clean
getContainers
washContainers
returnContainers
getContainers
8.2.2 LANDLORD
close.0
lastOrder.0
returnIngredients stop
waitOrder
serve
order
close.0
getContainer
lastOrder.0
getIngredient
waitOrder
getContainer close.1
getIngredients
prepareDrink
returnIngredients
34
CCSD
8.2.3 CLOCK
tick.2
close
tick.0
open
tick.1
8.2.4 CUSTOMER
35
CCSD
goToTable stop
close.0
moveToEnd drink
lastDrink.0
moveToFront
lastOrder.0
order
putdownContainer
serve
removeFromQueue
close.1
8.2.5 BARMAID
close.0 prepareDrink
waitOrder
order
getIngredients stop
returnIngredients
8.2.6 ORDERQUEUE
close.0 close.1
createCustomer stop
moveToEnd
moveToFront
removeFromQueue
36
CCSD
int count = 0; while (count < noOfCustomers) {// add customer to queue up to the maximum
orderQueue.addToQueue(cust); count++;
37
CCSD
try { Thread.sleep(QUEUE_INTERVAL); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { // queue has stopped write("queue has stopped"); return; } } }
Until a customer is created, the barmaid and landlord wait.(barmaid and landlord together will be referred to as servers here after) . When a customer is created the OrderQueue class informs the servers waiting on that class that a customer has arrived and assigns the customer to them.
public synchronized Customer getNextCustomer() { System.out.println(Thread.currentThread().getName() + "..............getNextCustomer"); System.out.println(queue.size() + " queue size " + "infront " + (inFront + 1)); while (queue.size() == (inFront + 1)) {// new customer has not joined queue try { System.out.println("no customer in queue"); wait();// wait till a new customer joins queue
38
CCSD
When the Customer is created he will start his thread by joining the end of the OrderQueue. At this point he is also notified the number of drinks he should order. Then he waits in the queue until the front of queue is reached. Once this happens, he goes in to the ServingArea. When he gets a server he makes the order, waits to get the drink, goes to the DiningArea to his defined table and drink. After drinking he will keep the cup or glass on the table if space is available, or otherwise, waits till assistant cleans the table.
private synchronized void live() { write(" has joined queue"); while (!isInFront) { try { write(" is waiting to move to front of queue"); wait(); } catch (InterruptedException e) { e.printStackTrace();
39
CCSD
while (!hasServer) { try { write(" is waiting for a server"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } write(server.getName() + " is assigned as server"); makeOrder(); while (!hasOrdered) { try { write(" is waiting to be served"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } write("customer " + getName() + " is making the order........."); while (!isServed()) { try {
40
CCSD
if (isLastDrink) { write(" ordering finished"); leaveBar(); } else { remainingDrinks--; write(" has " + remainingDrinks + " more drinks to order"); if (remainingDrinks == 1) { isLastDrink = true; } orderQueue.addToQueue(this); live();
41
CCSD
When the customer makes an order, it notifies the server as an order is being received. Then the server gets order details, gets relevant containers, ingredients, pours the drink, return ingredients and serve the customer. After customer is served the server wait for a new customer to arrive.
private synchronized void getOrder() { while (!customer.getOrdered()) { try { write("Waiting for customer to order"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // customer has ordered orderDrink = customer.getDrink(); notifyAll(); }
The assistant will be watching the DiningArea. He will watch the tables on regular intervals. If at least one table is unclean, he will walk to it and will clean the table. He will collect all the containers on the tables and wash and return them to cupboard. This action continues throughout the lifetime of the simulation.
public void clean() { if (tm.isClean()) {
42
CCSD
writeAssistant(" collected " + noOfCups + " unclean cups and " + noOfGlasses + " unclean glasses"); // clean tables tm.resetContainerCounts(); // wash containers writeAssistant(" is washing " + noOfCups + " cups and " + noOfGlasses + " glasses"); // returning containers cs.returnCup(noOfCups); gs.returnGlass(noOfGlasses); writeAssistant(" returned " + noOfCups + " cups and " + noOfGlasses + " glasses"); } }
The clock will keep track of the time the simulation has run. When there is only 10 time units left for the bar to close, he will notify the landlord.
while (ran > 0) { // write(String.valueOf(ran));
43
CCSD
44
CCSD
When customers hear this, the ones who have more drinks left to be ordered will finish the drink and will go back to queue. The fruit juice drinking customers will not wait to finish the drink if they need another drink. They will simply leave it on the table and rush to join the queue. The clock also notifies the landlord of close time. Landlord informs this to barmaid and assistant. When they hear the closing call, the servers will finish whatever order they are still serving, but will refuse new orders. The assistant will go through a single round of cleaning after closed. The landlord leaves the bar only after all customers, barmaid and assistant has left. This is the end of simulation.
public synchronized void isQueueEmpty() { while (!OrderQueue.getInstance().isEmpty()) { try { write("BAR IS CLOSED, BUT WAITING TILL ALL LEAVES>>>>>>>>"); wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } isBarEmpty = true; write("EMPTY..>>>>>>>>>>>>>>>>>>>>>"); notifyAll(); }
45
CCSD
10 TESTING
Event Customers enter bar at regular intervals Queue moves forward Queue stops adding customers when the configured no of customers are created, but adds customers who are already in the restaurant and are willing to order for the second time Queue stops when closing time is called Customers wait till moving to front to order drink Customers drink, put down container and leaves or goes for the next order round Barmaid and Landlord waits till customer is in front and ordered to start serving The servers collect the correct ingredients and containers for preparing drinks When one customer is served waits for another customer and repeat serving process Barmaid leaves bar at closing time Landlord and Barmaid use same queue, but behave independently A customer orders only a single drink at a time Servers serve only a single customer at a time Landlord calls last orders 10 seconds before simulation ends Landlord announces closing time Collecting containers reduces the number of containers in the cupboard Success
46
Asia Pacific Institute of Information technology When assistant returns containers, the number of containers change Collecting ingredients works correctly When one of server is using a particular ingredient, other server waits Customer moves to a favourite table randomly assigned Customers orders a drink, randomly assigned Customer waits till table is cleared to keep down the cup The fruit juice customers behaves as mentioned in last orders Table units are correctly assigned depending on type of drink being ordered Table units must not be controlled by customers Assistant waits for a rest time at the end of each cleaning rounds Assistant goes on cleaning rounds on configured times Assistant takes containers, washes and keep them back in cupboard After closing time is announced assistant, make the final round Assistant leaves bar after the final cleaning round Clock alerts landlord of last order call time and closing time The statistic test is performed Set drink orders to customers according to a ratio Configure times for tasks
CCSD
47
CCSD
11 SAMPLE OUTPUT
CUSTOMER
9 12:06:35:160 Thread-Customer-0 - has joined queue 11 12:06:35:161 Thread-Customer-0 - is waiting to move to front of queue 13 12:06:35:162 Thread-Customer-0 - has moved to front of queue 15 12:06:35:163 Thread-Customer-0 - barmaid is assigned as server 18 12:06:35:165 Thread-Customer-0 - is ordering Cappucino 19 12:06:35:166 Thread-Customer-0 - customer 0 is making the order......... 21 12:06:35:166 Thread-Customer-0 - is waiting for the order 32 12:06:35:172 Thread-Customer-0 - got the order 33 12:06:35:172 Thread-Customer-0 - is moving to table 3 35 12:06:35:173 Thread-Customer-0 - is drinking Cappucino 36 12:06:35:175 Thread-Customer-0 - has finished drinking Cappucino 37 12:06:35:176 Thread-Customer-0 - is going to put down cup 40 12:06:35:178 Thread-Customer-0 - has put down cup 41 12:06:35:178 Thread-Customer-0 - has 1 more drinks to order 43 12:06:35:179 Thread-Customer-0 - has joined queue 45 12:06:35:180 Thread-Customer-0 - has moved to front of queue 46 12:06:35:180 Thread-Customer-0 - is waiting for a server 47 12:06:35:181 Thread-Customer-0 - landlord is assigned as server 51 12:06:35:182 Thread-Customer-0 - is ordering Cappucino
48
CCSD
49
CCSD
TABLES
50
CCSD
INGREDIENTS
24 12:06:35:167 Thread-Barmaid Getting coffee from cupboard 25 12:06:35:168 Thread-Barmaid Getting milk from cupboard 27 12:06:35:169 Thread-Barmaid Returning coffee to cupboard 28 12:06:35:170 Thread-Barmaid Returning milk to cupboard
51
CCSD
CONTAINERS
22 12:06:35:166 Thread-Barmaid - getting 1 cup......remaining 5 54 12:06:35:184 Thread-Landlord - getting 1 cup......remaining 4 85 12:06:35:197 Thread-Barmaid - getting 1 cup......remaining 3 118 12:06:35:210 Thread-Landlord - getting 1 cup......remaining 2 146 12:06:39:163 Thread-Assistant - returning 4 cups....remaining 6
ORDERQUEUE
1 12:06:35:130 Thread-Queue - Order queue started...
52
CCSD
ASSISTANT
3 12:06:35:140 Thread-Assistant - Assistant started work 7 12:06:35:151 Thread-Assistant - Assistant cleaning round 0 due next 8 12:06:35:151 Thread-Assistant - is resting 139 12:06:39:152 Thread-Assistant - is cleaning 140 12:06:39:153 Thread-Assistant - collected 4 unclean cups and 0 unclean glasses 145 12:06:39:157 Thread-Assistant - is washing 4 cups and 0 glasses 148 12:06:39:165 Thread-Assistant - returned 4 cups and 0 glasses 149 12:06:39:166 Thread-Assistant - Assistant cleaning round 1 due next 150 12:06:39:167 Thread-Assistant - is resting
LANDLORD
4 12:06:35:140 Thread-Landlord - Landlord started work 6 12:06:35:151 Thread-Landlord - Landlord waiting for job 0 48 12:06:35:181 Thread-Landlord - got a customer - customer 0 49 12:06:35:181 Thread-Landlord - Waiting for customer to order
53
CCSD
BARMAID
2 12:06:35:140 Thread-Barmaid - Barmaid started work 5 12:06:35:149 Thread-Barmaid - Barmaid waiting for job 0 14 12:06:35:162 Thread-Barmaid - got a customer - customer 0
54
CCSD
55
CCSD
12 CRITICAL APPRAISAL
Java is one of the most flexible languages for concurrent programming when it comes to beginners. Apart from this point, the fact that Java supports high level object-oriented concepts is an added advantage when creating a simulation as this. The modelling techniques used here was LTS and FSP. They both provide easy understanding and application of concurrency. Therefore, been a beginner to concurrency, I found this background of assignment rather comfortable, than it would have been otherwise. The design is described above. It explains the use of the design concepts to Java language to implement the solution. This was a good start for concurrent programming. There are still a lot more in concurrent programming that still remains to be explored , and has created an interest in me.
56
CCSD
Magee J.,Kramer J.,(2006) Concurrency State Models and Java Programs, John Wiley and Sons Ltd.
Magee J.,(1997) , Label Transition System Analyser, [online] available from http://www.doc.ic.ac.uk/~jnm/LTSdocumention/LTSA.html[accessed 15th February 2011]
Microsoft MSDN,(2011),Coding Techniques and Programming Practices,[online] available from http://msdn.microsoft.com/en-us/library/aa260844(v=vs.60).aspx [accessed 19th February 2011]
Oracle,(2011),The Java Tutorials Concurrency, [online] available from http://download.oracle.com/javase/tutorial/essential/concurrency/index.html February 2011] [accessed 14th
Oracle, (2011), Java 2 Platform Standard Edition 5.0 API Specification,[online] available from http://download.oracle.com/javase/1.5.0/docs/api/ [accessed 14th February 2011]
57
CCSD from
http://www.developer.com/java/other/article.php/1025601
58