constraint automata with synchronization...

81
Constraint Automata with Synchronization Points M.F.A. Pouw Leiden Institute of Advanced Computer Science Student id: 0206113 E-mail: [email protected] Center for Mathematics and Computer Science E-mail: [email protected] Supervisor: Prof. dr. F. Arbab E-mail: [email protected] 15-06-2009 Abstract One of the most common methods to attain correct software is through its verification against a model. First the software is devel- oped and then a model for this software is created. The software is accepted as correct code when the model is verified. But this is only the case when the model correctly represents the software. In contrast, model-driven software development advocates developing the model first and deriving the software through a sequence of correctness- preserving model transformations. In this report, we describe CASP (Constraint Automata with Synchronization Points): a model-driven approach for developing concurrent, multi-threaded applications. With CASP first the verified model is built and then from this model the code is generated to coordinate the components in your program. Fi- nally, this coordinator and the components are combined as an opti- mized multi-threaded Java program. This thesis describes the steps that are required to develop the software tools to enable component based software development from a model point of view. 1

Upload: others

Post on 31-Dec-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Constraint Automata with Synchronization Points

M.F.A. PouwLeiden Institute of Advanced Computer Science

Student id: 0206113E-mail: [email protected]

Center for Mathematics and Computer ScienceE-mail: [email protected]

Supervisor: Prof. dr. F. ArbabE-mail: [email protected]

15-06-2009

Abstract

One of the most common methods to attain correct software isthrough its verification against a model. First the software is devel-oped and then a model for this software is created. The softwareis accepted as correct code when the model is verified. But this isonly the case when the model correctly represents the software. Incontrast, model-driven software development advocates developing themodel first and deriving the software through a sequence of correctness-preserving model transformations. In this report, we describe CASP(Constraint Automata with Synchronization Points): a model-drivenapproach for developing concurrent, multi-threaded applications. WithCASP first the verified model is built and then from this model thecode is generated to coordinate the components in your program. Fi-nally, this coordinator and the components are combined as an opti-mized multi-threaded Java program. This thesis describes the stepsthat are required to develop the software tools to enable componentbased software development from a model point of view.

1

Page 2: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Acknowledgements

After I finished a project for the Coordination and Component Composi-tion course given by Prof. dr. F. Arbab at the Leiden Institute of AdvancedComputer Science, I started my Master project at the Center for Mathe-matics and Computer Science. The research in SEN3 consists of interac-tion, composition, and coordination of concurrent distributed systems, andencompasses foundations, technology, and applications. My thesis advisorProf. dr. F. Arbab coordinates the SEN3.1 subgroup that mainly focuseson models and tools for coordination and composition. The course and myprevious project introduced to me some problems that occurred while coor-dinating components. See [7]. During my Master research project I used thegiven solution to solve this problem and I implemented several tools to helpprogrammers to coordinate components and to implement concurrent andcomponent based applications. I would like to thank Prof. dr. F. Arbab forthe possibility to do my Master research project in the SEN3.1 group andalso for all the help he and the people from SEN3 gave me to complete theresearch and my thesis.

2

Page 3: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Contents

1 Introduction 5

2 Reo 52.1 Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.3 Connectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.4 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3 Model transformations 103.1 Constraint automata . . . . . . . . . . . . . . . . . . . . . . . 113.2 Ports in CA . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.3 From Reo to CA . . . . . . . . . . . . . . . . . . . . . . . . . 12

4 Code generation 144.1 Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.2 Synchronization Points . . . . . . . . . . . . . . . . . . . . . . 15

4.2.1 Implementation . . . . . . . . . . . . . . . . . . . . . . 164.2.2 2phase get and put operations . . . . . . . . . . . . . 174.2.3 Time-outs . . . . . . . . . . . . . . . . . . . . . . . . . 264.2.4 Selector . . . . . . . . . . . . . . . . . . . . . . . . . . 274.2.5 Watchdog . . . . . . . . . . . . . . . . . . . . . . . . . 294.2.6 Read2Phase . . . . . . . . . . . . . . . . . . . . . . . . 304.2.7 Terminate . . . . . . . . . . . . . . . . . . . . . . . . . 33

5 CASP 345.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5.1.1 Coordinators . . . . . . . . . . . . . . . . . . . . . . . 355.1.2 Components . . . . . . . . . . . . . . . . . . . . . . . 43

5.2 Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.2.1 EMF . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.2.2 GMF . . . . . . . . . . . . . . . . . . . . . . . . . . . 455.2.3 Reo circuits model . . . . . . . . . . . . . . . . . . . . 465.2.4 Constraint automata model . . . . . . . . . . . . . . . 46

5.3 CASP editor . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.3.1 Drag-n-Drop . . . . . . . . . . . . . . . . . . . . . . . 485.3.2 Connections . . . . . . . . . . . . . . . . . . . . . . . . 495.3.3 Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

5.4 Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . 50

3

Page 4: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

6 Examples 516.1 Time-Temperature . . . . . . . . . . . . . . . . . . . . . . . . 51

6.1.1 Components . . . . . . . . . . . . . . . . . . . . . . . 526.1.2 Coordinator . . . . . . . . . . . . . . . . . . . . . . . . 536.1.3 CASP model . . . . . . . . . . . . . . . . . . . . . . . 55

6.2 Fibonacci . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566.2.1 Component . . . . . . . . . . . . . . . . . . . . . . . . 566.2.2 Coordinator . . . . . . . . . . . . . . . . . . . . . . . . 586.2.3 CASP model . . . . . . . . . . . . . . . . . . . . . . . 58

6.3 Dining philosophers . . . . . . . . . . . . . . . . . . . . . . . 596.3.1 Components . . . . . . . . . . . . . . . . . . . . . . . 606.3.2 Coordinator . . . . . . . . . . . . . . . . . . . . . . . . 616.3.3 With dead-locks . . . . . . . . . . . . . . . . . . . . . 626.3.4 Without dead-locks . . . . . . . . . . . . . . . . . . . 636.3.5 Dead-locks solved with time-outs . . . . . . . . . . . . 64

7 Correlated work 657.1 Webservices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657.2 Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

8 Conclusion and Future development 66

A Example code 68A.1 Time-Temperature . . . . . . . . . . . . . . . . . . . . . . . . 68

A.1.1 Clock component . . . . . . . . . . . . . . . . . . . . . 68A.1.2 Display component . . . . . . . . . . . . . . . . . . . . 69A.1.3 Generated CASP code . . . . . . . . . . . . . . . . . . 69

A.2 Fibonacci . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71A.2.1 Sum component . . . . . . . . . . . . . . . . . . . . . 71A.2.2 Generated CASP code . . . . . . . . . . . . . . . . . . 72

A.3 Dining philosophers . . . . . . . . . . . . . . . . . . . . . . . 73A.3.1 Philosopher component . . . . . . . . . . . . . . . . . 73A.3.2 Generated CASP code with dead-locks . . . . . . . . . 76A.3.3 Generated CASP code without dead-locks . . . . . . . 79A.3.4 Generated CASP code solved dead-locks with time-outs 79

4

Page 5: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

1 Introduction

When developing model-driven concurrent software through a sequence ofcorrectness-preserving model transformations, the first model must be awidely used and known model that, after each transformation, still containsall the information that is necessary for deriving the software. To have abroader selection of usable and not too complex models, the computationalpart and the coordination part of the software are separated and the focusis set on a model for the coordination part.

These coordination models can serve as a basis for component basedsoftware engineering, a programming methodology to create new softwarebased on existing building blocks, called components. The coordinationparadigm defines how and when data is communicated between the compo-nents. The components in this paradigm are seen as black box entities. Forexogenous models, the coordination of the behavior of these entities is donewithout their knowledge, from outside of those entities [3]. The behavior ofa composition of components can be changed without changing the compo-nents themselves. This makes it possible to create different programs withdifferent behavior out of exactly the same components.

The CASP approach for developing model-driven concurrent softwareonly focuses on the model for coordinating components and later adds thecomponents. The language that is used for this model is Reo, an exoge-nous coordination model to coordinate components. Because Reo providesa comprehensive set of modeling tools such as editors, model checkers, andsimulators [5], this is a suitable language for our coordinating model.

The details of Reo are described in the first part of this thesis. After Reothe details of the CASP approach with constraint automata are explainedand how we use this automata as a second model after the first transforma-tion. The constraint automata is the model from which the Java code forthe coordination of the components is generated. Then the implementationdetails of this Java code are described. Finally, the implementation of themodels and the CASP project in Eclipse are shown, supported by a numberof examples.

2 Reo

Reo is a channel based exogenous coordination model to coordinate compo-nents [1]. The coordination in a Reo model is done by connectors. Theseconnectors are built compositionally out of a set of simple channels. A chan-

5

Page 6: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 1: Examples of different channel types in Reo [4]

nel can be connected to another channel with a node. A node is a statelessplace that only can read data from a single input and write this data directlyto all of its existing outputs. Reo does not focus on the components, butfocuses only on channels, connectors, their composition and the behavior ofthe constructed Reo circuits [3].

2.1 Channels

Channels in Reo are primitive communication media, each with exactly twoends. There are two types of channel ends, namely a source or a sink end.Data always enters a channel via a source end and exits the channel via asink end. A simple example is a directed channel that has only a sourceend and a sink and, thus data flows from the source end to the sink end.With a synchronous channel this happens synchronously. Such a channel isa stateless primitive, so data cannot be stored in the channel, neither in thesource nor the sink end, but flows directly from one end to the other end ofthe channel.

There are two operations that can be executed on the channel ends. Theread and the write operation. Data is read from and written to a channelend. If this channel end is a source end, only the write operation is possible.If the channel end is a sink type channel end, only the read operation ispossible. The type and the amount of data that can be read or written to achannel end is not specified.

Another stateless channel is a lossy synchronous channel that can losethe data between the two ends when the operations on the channel ends areasynchronous. For storing data in a channel the FIFO channel can be used,the data is stored in a buffer by the first in, first out principle. Channelswith buffers can be in an empty or in a full state.

Channels with two source ends or two sink ends are called drains andspouts, respectively. A synchronous drain will receive data from both sourceends synchronously and then this data is lost. The synchronous spout createsdata whose content is not specified, and sends them synchronously to bothof the channel sink ends. The asynchronous versions of the drain and the

6

Page 7: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 2: Examples of nodes in Reo [4]

spout channels receive and send data asynchronously [3].This combination of end types with the types of channels give the possi-

bility to create many different user defined channels for their own purpose.This definition for synchronization, buffering, ordering and data retentionor loss of a channel can be described as a different data constraint for eachchannel. The graphical representation of each channel depends on theirsemantics. See Figure 1 on page 6 for examples of different channels.

2.2 Nodes

The concept of nodes is used in Reo to combine channels together. A nodeis not a component or a buffer where data can be stored, but a statelessprimitive that is used to move data from one channel directly to anotherchannel. There are three different types of nodes, namely a source, a sinkand a mixed node. A node is called a source node when the connectedchannel ends are all of the type source end. When all the connected channelends are of the type sink end, the node is called a sink node. If a combinationof channel end types are connected, the node is called a mixed node [3].

The read and write operations of components on nodes are only possibleon source and sink nodes, not on mixed nodes. A write operation on a sourcenode can succeed only when all connected channel source ends accept thewritten data. If accepted, the data is replicated by the source node to allconnected channels. On the sink node only read operation can be performed.A read operation can only succeed when at least one connected channel sinkend offers a data item. If multiple connected channels offer a data item,one is selected non-deterministically. A sink node is called a merger and asource node is called a replicator.

A mixed node combines the behavior of the merger and the replicator.Non-deterministically a data item is selected from the connected channelsink ends and this data is atomically replicated to all connected channelsource ends, but only when all connected channel source ends accept thewritten data. See Figure 2 on page 7 for examples of the different nodetypes.)

7

Page 8: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 3: Example of a Reo circuit [4]

2.3 Connectors

The combined channels in a Reo model are called a connector, this can bea single channel or multiple channels connected by one or more nodes. Thechannel ends that do not connect to a node are the connector ends. See F,E and B in Figure 3 on page 8. These ends can be used to write data to andto read data from the connector, depending on its semantics. Because of thesynchronous nature of this connector, all operations on a single connectoroccur at the same time.

To ensure that all operations on a single connector occur at the sametime, not all operations are possible. The best way to find possible exe-cutions of a connector is to propagate the operations through the channelsto see where read and write operations meet and which operations are notneeded or are necessary to complete an execution.

The example in Figure 3 shows an exclusive router in Reo. Operationscan be executed on the connector ends F, E and B. The channel end in Fis a source type channel end, a write operation can be executed on F. Thechannel ends E and B are sink type channel ends, read operations can beperformed on these ends. From F to X a synchronous channel propagatesthe write operation to a replicator node. From this node the operationis replicated over two lossy synchronous channels to M and N. And theoperation is replicated to a synchronous drain that is also connected to Z.The data from this operation can be lost in the channel between X and M,or in the channel between X and N. Data from a write operation can only

8

Page 9: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

flow into the synchronous drain if there is also data, from a write operation,that flows from Z into the synchronous drain. From M and N, the operationis replicated again via synchronous channels to W, U, E and B. W and Uare merged with a merger node into Z. So the data of only one of theseoperations can flow into the synchronous drain.

If we want a possible execution of this connector to complete, then theremust be a write operation on the channel end F, and at least one readoperation on E or B. Then these operations propagate through the channelsand over the nodes. The merger node W, U, Z nondeterministically selectsthe read operation from one of the channels. The data flows from X throughthe lossy synchronous channel on the side of the selected operation, and thedata is lost in the lossy synchronous channel on the other side. Then thedata of this operation propagates into the synchronous drain, just like thedata from the replicator node X. Finally the data from one of the lossysynchronous channels reaches exclusively one of the read operation of E orB. This Reo model makes sure that for every possible execution the inputdata is never replicated to more than one of the output ports.

2.4 Components

The operations on the connector ends are executed by components. Theycan connect to these channel ends by ports. These ports are input ports oroutput ports. The input ports can connect to connector ends that are of thechannel end sink type and the output ports can connect to the connectorends that are of the channel end source type.

The components are black box entities with their own timing and oper-ation. The communication in the component is component specific, but thecommunication to the outside of the component is done only by the readand write operations on these ports. Each component only knows aboutitself and the number and types of its ports.

The connector to which the components are connected, operates depend-ing on its semantics and the available operations. The information about thenumber of components and the type of components is not needed by the con-nector. It only collects the operations that are executed by the componentsand tries to complete an execution of the connector.

The internal behavior of a component depends on how the component isbuilt. It can be a software component or even a hardware component. Theoverall behavior of the combined components fully depends on the semanticsof the connector.

If a component executes a read or a write operation on a port, the

9

Page 10: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 4: Example of a constraint automata [4]

component has to wait until this operation is complete by the connector.This depends on the structure of the connector and the operations on otherports by other components. As long as there is no possibility to complete anexecution, all the components that attempt an operation, have to wait untilthere is a combination of operations so that the connector can complete anexecution.

3 Model transformations

The goal for the CASP approach of developing model-driven software is togenerate correct programming code that simulates or executes the coordi-nation of the components, like in the Reo model, but then, as a program.There are a lot of different approaches for executing the Reo model [8].For code generation, the most suitable are the constraint automata. Theseautomata consist of states and transitions that are easily converted to thestates of objects in a program and to methods to change these states.

Reo is a stateless model, except for the channels with buffers. Theconstraint automaton of a Reo connector contains the necessary informationfrom the Reo model so that it can be used to generate the programming code.

The first step of the CASP approach is to convert Reo models to con-straint automata and then generate the programming code for this constraintautomata that can be executed to coordinate the components like the Reomodels do.

10

Page 11: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

3.1 Constraint automata

Constraint automata provide an operational semantics for Reo circuits [4].A constraint automaton over the data domain Data is a labeled transitionsystem model with states and transitions. This can be seen as a tuple A =(Q, Names,→, Q0) where

• Q is a set of states,

• Names is a finite set of names,

• → is a subset of Q× 2Names ×DC ×Q, called the transition relationof A,

• Q0 ⊆ Q is the set of initial states.

A transition is written as qN, g−−→

p where N is the name-set and g the guardof the transition. There are two requirements for each transition

1. N 6= 0

2. g ∈ DC(N, Data)

The constraint automaton in the example in Figure 4 on page 10 has a startstate q0 and from this start state there are two transitions, one to state p0and another to state p1. There are also two transitions back to state q0,one from each of the states p0 and p1. The transitions have labels (name-set) and data constraints (guards). Depending on these labels and dataconstraints other states can be reached via the transitions.

3.2 Ports in CA

The input and output ports of the components in Reo are used for the labelsin the constraint automata. The label of the transition defines which portsare necessary for the data constraint. The port can be an input port or anoutput port, if the port in the label and the constraint is an input port, thedata that is read from this port is tested in the constraint. If the port inthe label and the constraint is an output port, the value of the data is setwith the constraint and is written to this port.

In the example in Figure 4 the constraint automaton for a FIFO1 bufferis given. The data domain of this constraint automaton is 0 and 1. If datais written to the FIFO1 in the first transition, then the data is read from theFIFO1 in the next transition. Therefore this FIFO1 has two ports, A and B.

11

Page 12: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

A is the input port and B is the output port. The transition from state q0to p0 has a label with port A, the value of the data from this input port istested with the constraint. If this value is equal to zero, the data constraintis true and state p0 can be reached via this transition. From p0 there isonly one transition back to p0. This transition has a label with output portB. The value of the data on this port is set to zero when this transition istaken. So, if data is read from port A in the first transition, then this samedata is written to port B the next transition.

The other transition from q0 to p1 does exactly the same, but then statep1 can only be reached via the transition when the data that is read frominput port A is equal to one. Then state p1 is reached and the next transitionthe same data is writtento output port B. If these states and transitions arecombined, this constraint automaton behaves like a single bounded first in,first out, buffer.

With constraint automata all possible states and all the transitions fromand to these states can be defined. The labels and the data constraintson these transitions give the possibility to define strict semantics for eachautomata. If there are multiple automata that should be combined, thenthere are strict rules on how to calculate the product of these constraintautomata to create a single, more complex constraint automaton.

The product of two constraint automata A1 = (Q1, Names1,→1, Q0,1)and A2 = (Q2, Names2,→2, Q0,2) is:

A1 1 A2 = (Q1 ×Q2, Names1 ∪Names2,→, Q0,1 ×Q0,2)

where → is defined by the following rules:

q1N1, g1−−−→1p1, q2N2, g2−−−→2

p2, N1 ∩Names2 = N2 ∩Names1

〈q1, q2〉N1 ∪N2, g1 ∧ g2−−−−−−−−−−−→〈p1, p2〉

andq1N, g−−→1

p1, N ∩Names2 = 0

〈q1, q2〉N, g−−→〈p1, q2〉

and latter’s symmetric rule [4].

3.3 From Reo to CA

In Reo, simple channels can be combined with nodes into more complexconnectors and the semantics of these connectors can be defined as dataconstraint. This is just like combining small constraint automata with data

12

Page 13: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 5: Examples of constraint automata for some basic connectors [4]

constraints into bigger, more complex constraint automaton by taking theirproduct.

The constraint automata model is defined to serve as the semantics ofReo connectors, so as a Reo connector needs operations of components oninput or output ports that are connected to the channel ends, a constraintautomaton requires data from a port in the label of a transition. Reo mod-els thus can easily be converted to a constraint automaton without losingimportant information to coordinate components. The constraint automatamodel contains the needed states from the coordination so that is becomeseasier to generated programming code from this model [4].

For each possible Reo channel the semantics is defined by a constraintautomata, like the examples in Figure 5 on page 13. These constraint au-tomata can be combined by calculating their product [4]. Therefore it ispossible to create a constraint automaton for each Reo connector, becauseeach connector is a combination of Reo channels [4].

Unfortunately the calculated constraint automaton is not always themost optimal automaton. There are more details and transitions visiblethan there are needed to enable the required operations. To make thisconstraint automaton the most simple automaton, a technique called hidingis used. With this technique all the details and internal states that are of nointerest are hidden and yield a simpler automaton where only the necessarydetails are made observable. See [4] for more information and examples ofhiding.

13

Page 14: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 6: Constraint automaton and corresponding simulation table

4 Code generation

Now that the coordination can be modeled with Reo and the Reo connec-tors can be converted to a constraint automata, the states from this lastmodel are used to generate programming code. The first part of this codegeneration consists of simulating the constraint automaton. From this sim-ulation a standard template is extracted and this template is then used togenerate programming code from every possible constraint automaton andthus indirectly from every possible Reo connector.

For the simulation the model of the constraint automata is converted toa table with all the information of the constraint automaton, like the states,the nodes and the data constraints. In Figure 6 on page 14 the constraintautomaton for the exclusive router is given, with the corresponding simula-tion table. The ports and the type of ports, I for input and O for output,are given in the first row. For each transition there is a row with the startstate of the transition, the end state of the transition, the ports that aregiven in the label of the transition, 0 if the port is not in the label, 1 if theport is in the label, and the data constraint for this transition.

With this table, a simple loop can show which transitions are possiblefrom the current state and which ports are needed for these transitions.Ignoring the data constraints, the information in the table is enough tosimulate the constraint automaton, when you know the current state and ifthe necessary ports are available.

The data from the ports in the constraint automata correspond to thedata from the operations of the components in the Reo. If you want to knowif a necessary port is available in the constraint automata, then you actuallyneed to know if there is an operation executed on this port by a component.And to find out if a transition can be taken, not only all necessary portsshould be available, also the data constraint of the transition with the datafrom these operations should be true.

14

Page 15: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

4.1 Semaphores

To make sure that all necessary ports for a transition are available, i.e.,if an operation is executed by a component on every one of them, eachoperation is blocked while testing the other ports. If all necessary portsare available, the operations are unblocked and all of these operation areexecuted synchronously, i.e., the transition is taken. If not all necessaryports are available, the transition cannot be taken and the operations stayblocked.

The blocking of operations by the connector is done by semaphores.A semaphore is a common method to ensure that a critical section or aprotected variable is accessed only by one single object at the time. If it isaccessed, the semaphore is locked, else the semaphore is unlocked. In eachport a locked semaphore is defined. This lock, blocks each operation by acomponent on the port until the semaphore is unlocked by the connector.This way the components and the coordinator become synchronized.

Unblocking operations on ports by unlocking the semaphores on theseports can only be done by the connector. This is done by two phase syn-chronization, the first phase checks if all necessary operations on the portsfor a transition are available. If this is the case, the second phase unblocksthe operations by unlocking the semaphores. If this is not the case, thesemaphores stay locked and the operations stay blocked.

4.2 Synchronization Points

When time-outs are added to the operations, components can retract anoperation on a port. If such retraction occurred after the first synchro-nization phase and before the second synchronization phase, the retractedoperation cannot be executed in the second phase. To overcome this flawthe operations should be locked during the first synchronization phase todisable a possible retraction by a time-out. For this lock each port requiresmore than one semaphore. These semaphores are combined into a so calledsynchronization point: a data structure that consists of multiple semaphoresto ensure synchronous execution of transitions by the connector.

Instead of a single semaphore, now each port has its own synchroniza-tion point. With this synchronization point the two phase synchronizationis extended with extra locks for each operation. The first phase checks ifall necessary operations for a transition are available and locks the syn-chronization point to ensure that the operation cannot be retracted by thecomponent. If not all necessary operations are available, all locked synchro-

15

Page 16: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

nization points are unlocked so that the operations can retract by a time-out,but the operation stays blocked because the transition is not taken and noneof the operations is executed.

If all necessary operations are available, the transition will be taken,i.e., the necessary operations must be executed. They are unblocked, theyexecute and finally each synchronization point is unlocked because there isno operation left with a time-out to retract.

4.2.1 Implementation

A synchronization point consists of several semaphores. The following semaphoresare used in a synchronization point: syncPointLock, twoPhaseStatusLock,exchangeBufferFull, exchangeBufferEmpty and the selectorLock. When anoperation is started on a port, the operation is blocked by locking the sync-PointLock semaphore. During the first synchronization phase the synchro-nization point is locked by the twoPhaseStatusLock. Now the operationcannot retract anymore. If not all necessary operations are available afterthe first phase, all synchronization points are unlocked by unlocking thetwoPhaseStatusLock. The operations can be retracted until a next firstphase, but are still blocked by the syncPointLock semaphore.

public Object get() {return get(-1);

}

public Object get(int timeOut) {syncPointLock.lock();return getInternal(timeOut);

}

public boolean put(Object obj) {return put(obj,-1);

}

public boolean put(Object obj, int timeOut) {syncPointLock.lock();return putInternal(obj, timeOut);

}

When all the necessary operations are available, the operations can beexecuted, this is done in the second synchronization phase. During thisphase the data from a write operation is moved to a read operation via a

16

Page 17: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

buffer. This buffer is protected by the exchangeBufferFull and exchange-BufferEmpty semaphores to make sure that first the data is written in thebuffer and then the data is read from the buffer and not in a different order.

public boolean readyToGet() {boolean correctCall = false;twoPhaseStatusLock.lock();if (status == free) {

correctCall = true;status = ready2get;

}twoPhaseStatusLock.unlock();if (!correctCall) {

throw new RuntimeException("readyToGet() called while inanother two-phase operation");

}syncPointLock.lock();if (count < 0) {

return true;} else {

status = free;syncPointLock.unlock();return false;

}}

Finally the selectorLock is used to read and write safely to and from an arrayof selectors, these selectors are used when multiple operations are started ona single synchronization point. This is explained in the Multiple Selectionsection.

The synchronization point class implements the interfaces that are usedby the components and the connector to connect to the synchronizationpoint. These interfaces hide several methods of the synchronization pointso that it operates correctly. The methods that are available for the compo-nents are the put() method for a write operation and the get()method forthe read operation. There is also the terminate() method to pass terminatesignals through via the synchronization point. The connector is able to useall methods. These connector specific methods are readyToPut(), readyTo-Get(), put2phase(), get2phase(), read2phase() and the end2phase().

4.2.2 2phase get and put operations

Each port of a component connects to a coordinator by its own synchro-nization point. A component starts a read or write operation on a port by

17

Page 18: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 7: 2phase operations with three components18

Page 19: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

calling the put() or get() method on the synchronization point of that port.Both these methods lock the syncPointLock semaphore and the operation isblocked. As long as there is no time-out or the operation is not executed, theoperation stays blocked and the component cannot continue as well. Theblocking and continuation of operations are handled in the getInternal() andthe putInternal() methods, these methods are explained in the Internal getand put operations section.

public boolean readyToPut() {boolean correctCall = false;twoPhaseStatusLock.lock();if (status == free) {

correctCall = true;status = ready2put;

}twoPhaseStatusLock.unlock();if (!correctCall) {

throw new RuntimeException("readyToPut() called while inanother two-phase operation");

}syncPointLock.lock();if (count > 0) {

return true;} else {

status = free;syncPointLock.unlock();return false;

}}

The connector tries to take one transition at the time by checking the theports for necessary operations of the current transition. For a necessaryget operation on a port, the readyToGet() method on the synchronizationpoint of that port is called, for a necessary put operation on a port, thereadyToPut() method on the synchronization point of that port is called.These methods lock the synchronization point by locking the twoPhaseSta-tusLock semaphore and return true if the operation is available and false ifthe operation is not available. If not all necessary operations are available,the synchronization points are unlocked by calling the end2phase() methodon the synchronization point for each port.

public void end2Phase() {semaphore.unlock();twoPhaseStatusLock.lock();

19

Page 20: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

if (status != free) {syncPointLock.unlock();

}status = free;twoPhaseStatusLock.unlock();

}

If all necessary operations on the ports are available, during the second syn-chronization phase the get2phase() and put2phase() methods are called onthe synchronization points of these ports, depending on the type of opera-tion. These methods move the data from the write operation to the bufferin the synchronization point by unlocking the exchangeBufferFull and lock-ing the exchangeBufferEmpty. They then move the data from the bufferto the read operation by unlocking the exchangeBufferEmpty and lockingthe exchangeBufferFull. Then, just like the end2phase() method, the syn-chronization points are unlocked and finally the operations are unblockedby unlocking the syncPointLock semaphores.

public Object get2Phase() {boolean correctCall = false;twoPhaseStatusLock.lock();if (status == ready2get) {

correctCall = true;status = free;

}twoPhaseStatusLock.unlock();if (correctCall) {

return getInternal(-1);};throw new RuntimeException("get2Phase() call must follow

a call to readyToGet()");}

The read2phase() method is used when a transition uses data constraints,this is explained in the Read2Phase section.

public boolean put2Phase(Object obj) {boolean correctCall = false;twoPhaseStatusLock.lock();if (status == ready2put) {

correctCall = true;status = free;

}twoPhaseStatusLock.unlock();if (correctCall) {

20

Page 21: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

return putInternal(obj, -1);};throw new RuntimeException("put2Phase() call must follow

a call to readyToPut()");}

Internal get and put operations

The blocking and continuation of operations are handled in the getInternal()and the putInternal() methods, the simplified flow charts of these methodsare shown in Figure 8 on page 22 and Figure 9 on page 23. Both methodsuse the count variable of the synchronization point and their own myCountvariable to store the number of read and write operations. After an op-eration the getInternal() or putInternal() method is called. If there is an-other complementary operation available, both operations are completed. Ifthere is no other complementary operation available, this operation is en-queued with the enqueueReader() or enqueueWriter() method. Both meth-ods are based on the enqueueReader() method that creates and returnsa locked semaphore. When the other complementary operation calls theputInternal() or getInternal() method, this semaphore is unlocked by thedequeueReader() or dequeueWriter() method and both operations can becompleted.

private Semaphore enqueueReader(int timeOut) {return enqueueReader(null, timeOut);

}

private Semaphore enqueueReader(Object obj, int timeOut) {Semaphore semaphore;if(timeOut != -1){

new WatchDog(select, timeOut).start();}semaphore.lock();return semaphore;

}

private void dequeueReader() {semaphore.unlock();

}

private Semaphore enqueueWriter(Object obj, int timeOut) {return enqueueReader(obj, timeOut);

}

21

Page 22: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 8: Main flow of getInternal() method

22

Page 23: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 9: Main flow of putInternal(object) method

private void dequeueWriter() {dequeueReader();

}

In the enqueueReader() method a part of the time-out mechanism is shown,this mechanism is discussed in the time-out section. Later, also multipleoperations are discussed. By enabling multiple operations the semaphorein the synchronization point is replaced by the selector data structure thatensures the correct selection of the operations and the time-outs.

Example

The example in Figure 10 on page 24 shows a small constraint automatonand its corresponding simulation table. The Reo model from which thisautomaton is created consists of three components that connect to a coor-

23

Page 24: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 10: Constraint automaton and corresponding simulation table

dinator. Component A has an output port A1 to write data to the inputport B1 of component B. Component B also has an output port B2 to writedata to the input port C1 of component C. The constraint automaton hasonly one state and two transitions to simulate the coordinator for this Reomodel. In the first transition data from port A1 is read and written to portB1, the second transition reads data from port B2 and writes this to portC1.

The simulation of this example is shown in Figure 7 on page 18. Thisdiagram shows the three components A, B and C. The ports of these com-ponents correspond to the four synchronization points A1, B1, B2, C1. Theright hand side shows the connector, i.e., the coordinator with the two pos-sible transitions. The components and the connector call several methodson their own synchronization points in order to execute both transitions.

First component C performs a get operation, this is done by calling theget() method of the connected synchronization point. After this operation,the component is blocked and cannot continue until the connector completesthis operation.

The connector has two possible transitions, transition one requires aput operation from component A on synchronization point A1 and a getoperation from component B on synchronization point B1. The secondtransition requires a put operation from component B on synchronizationpoint B2 and a get from component C on synchronization point C1. Theconnector first tries to execute the first transition with a two phase operationby calling the readyToPut method of synchronization point A1, by doingthis, A1 is locked and the call returns false, because there is no put operationavailable on A1. The connector cannot continue the two phase operation,thus it unlocks A1 by calling the end2phase of A1.

Because the first transition could not be completed, the connector triesthe next transition, also with a two phase operation. It starts by calling thereadyToPut method on B2, this synchronization point becomes also locked,but component B didn’t execute an operation on B2, thus B2 is also unlockedafter returning false and ending the two phase operation with the end2phase

24

Page 25: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

method. During this two phase operation, component A executes a writeoperation on A1 by calling the put() method. After this call, A is blockedand cannot continue until the connector completes this operation.

Now the connector tries to execute the first transition again, but becauseof the write operation of component A on A1. The readyToPut() methodreturns true instead of false and the next operation of the first transitioncan be tested. Unfortunately the readyToGet() method on B1 returns falseand the two phase operation cannot be completed. First synchronizationpoint A1 is unlocked and then B1 is unlocked. Just like before, the nexttransition is tested by the connector, but because there is still no operationfrom component B on synchronization point B2, this transition is also notcompleted.

During the last two phase-operation on the second transition, compo-nent B executed a read operation on synchronization point B1. Now allnecessary operations for the first transition are available. A1 is locked againby calling the readyToPut() method, it returns true to the connector. B1 islocked by calling the readyToGet() method and it also returns true to theconnector. Now the first phase is completed and the connector can start thesecond phase by calling the put2phase on A1 and the get2phase on B1. Theput2phase is called first to move the data from the put() operation of com-ponent A into the buffer of the coordinator. Next, the get2phase is calledto move this data from the buffer to the get() operation of component B.Finally synchronization points A1 and B1 are unlocked and the read andwrite operations of the components A and B are completed. Now thesecomponents are unblocked and they can continue their own execution.

After completing the read operation of component B on synchronizationpoint B1, B directly executes a write operation by calling the put() opera-tion on synchronization point B2. Component B is blocked again and theconnector continues by testing the second transition for execution. The firstphase is started by calling the readyToPut() method on B2, B2 is lockedand returns true. Now the readyToGet() method is called on synchroniza-tion point C1, because component C already executed a read operation inthe beginning of the example, it has been blocked for a while, but it returnstrue to the connector.

Now the first phase of the second transition is completed and the secondphase is started by calling the put2phase() method on synchronization pointB2. This method moves the data from the put() operation of component Binto the buffer of the coordinator. Next the get2phase() method is called tomove the data from the buffer to the get() operation of component C. B2 andC1 are unlocked, the operation is completed and component B and C are

25

Page 26: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 11: Two operations with time-outs on different synchronizationpoints

unblocked. Now all components can continue their own execution and newoperations on the synchronization points can be executed. The connectoralso continues its own execution by testing the first transition again.

Multiple operations

If a component does not use multiple threads, doing multiple operations onmultiple ports can lead to a dead-lock. For instance, if the operations ontwo ports of a component are necessary for a single transition and these op-erations inside the component are started sequentially one after each other,the component blocks on the first operation. The second operation is neededfor the connector in order to execute the transition, but because the com-ponent blocks on the first operation, this second operation is never started.Unless this component uses time-outs the component stays blocked. If thesequential order of the execution of the operations by the component issemantically important, then the coordinator must follow a protocol thatrespects this order, as well. In this case, there will not be a transition thatinvolves both operations. Otherwise the two operations should be startedin two separate threads.

4.2.3 Time-outs

Each thread of a component that executes an operation will block untilthis operation is completed. In the most optimal case this blocking onlytakes the amount of time that is needed for the connector to check the otheroperations for availability. But in some cases not all necessary operations are

26

Page 27: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

available and the thread or the whole component is blocked longer. In theworst case the connector dead-locks and all components will block foreveron their last operation. To overcome this possible problem an operation canbe started with a time-out parameter. This time-out is given in millisecondsand if the operation is blocked this number of milliseconds, the operation isretracted by the component. The return value of the operation is false andthe component can continue with other operations.

In Figure 11 on page 26 a graphical representation of the execution oftwo separate operations with time-outs is given. The first operation returnsfalse because of a time-out, the second operation is able to continue. Thetwo operations are executed by a component on different synchronizationpoints. A synchronization point creates a watchdog thread for each opera-tion with a time-out. When the connector performs the first phase of a twophase operation, the readyToPut() method of the synchronization point iscalled. If the operation has a time-out, the watchdog fakes the completionof the operation by sending the return value false to the component and theconnector. The component knows that the operation timed out because ofthe false value, and the connector receives the information that there is noavailable operation.

With the second operation, the readyToPut() method is finished beforethe time-out can fake the completion of the operation by sending false to theconnector. The readyToPut() returns true and the connector knows that anoperation is available. The component does not receive a return value fromthe synchronization point until the second phase is finished. If the connectoris not able to finish the second phase and the end2phase() method is calledto unlock the synchronization point, the operation still times out because atime-out bit is set in the selector of this synchronization point.

4.2.4 Selector

A component that consists of several threads can start one operation perthread resulting in multiple operations on a single (or more) synchroniza-tion points. Some of these operations may have time-outs and the selectionof an operation by the connector should occur nondeterministically. Thesefeatures are implemented by the selector in the synchronization point. Foreach operation a selector is created, this selector consists of a semaphoreand three variables. The semaphore ensures the blocking of the operationuntil it is completed or timed-out. The variables are the booleans status,selected and timeOut.

27

Page 28: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

public class Selector {private boolean status = true;private boolean selected = false;private boolean timeOut = true;private Semaphore semaphore;

public Selector() {semaphore = new Semaphore(0);

}

public void setStatus (boolean status) {this.status = status;

}

public boolean getStatus(){return status;

}

public void setSelected (boolean selected) {this.selected = selected;

}

public boolean isSelected(){return status;

}

public void lock(){semaphore.lock();

}

public void unlock(){semaphore.unlock();

}

public void setTimeOut(boolean timeOut) {this.timeOut = timeOut;

}

public boolean isTimeOut() {return timeOut;

}}

The coordinator inquires a possible operation from the synchronization points,the synchronization point selects one selector nondeterministically. This se-

28

Page 29: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

lector belongs to a single operation, if this operation is able to complete,then the status variable of this selector is true. When the operation cannotcomplete because of a time-out, the status variable of this synchronizationpoint is false. When the coordinator starts the second phase the booleanselected from this selected selector is changed from false to true. Now theoperation of this selector will be completed and cannot time-out anymore.But when the operation does time-out before the coordinator starts thesecond phase, the timeOut boolean will be set to true and this operationwill time out. The component and the coordinator will both receive a falsereturn value and this selector cannot be selected anymore.

4.2.5 Watchdog

For each operation a selector is created in the synchronization point. Whenthe operation has a time-out enabled, the synchronization point adds awatchdog thread to this selector. This watchdog thread waits until thenumber of milliseconds is passed and then sets the timeOut boolean of theselector to true and unlocks the selector of this operation.

public class WatchDog extends Thread{private Selector selector;private int timeOut;

public WatchDog (Selector selector, int timeOut){this.selector = selector;this.timeOut = timeOut;

}

public void run() {try{

Thread.sleep((long)(timeOut));}catch (InterruptedException e) {

// ignored}selector.setTimeOut(true);if(!selector.isSelected()) {

selector.setStatus(false);selector.unlock();

}}

}

29

Page 30: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Because the timeOut boolean of the selector is true, it knows that this oper-ation will complete because of a time-out and not by another complementaryoperation. The operation is unlocked and the component receives false asthe return value. The operation of the component is timed out and the com-ponent is not blocked anymore. The watchdog and the selector are removedfrom the synchronization point. If the time-out occurs after a normal com-pletion of the operation by a complementary operation, the selected variableof the selector is true and the watchdog is removed.

4.2.6 Read2Phase

A connector implements the transitions of the constraint automata. Thesetransitions do not only define the needed operations on the necessary portsbut also the data constraints for these operations. Only when the data of alloperations match the constraints of the transition, the connector can executethe operations for this transition. When the connector wants to match thedata of an operation, it needs to execute a second phase get operation inorder to get the data and to test this with the data constraint. Because ofthis execution the component will unblock and continues. When the dataof this operation matches the data constraint this is no problem, but whenthe constraint is not met, the second phase get operation should not havebeen executed. Unfortunately this operation cannot be reversed. To solvethis, a second phase read operation is added to the second phase put andget operations of the connector.

public Object read2Phase() {boolean correctCall = false;twoPhaseStatusLock.lock();if (status == ready2get) {

correctCall = true;}twoPhaseStatusLock.unlock();if (correctCall) {

if(readSelector == null) {selectorLock.lock();int i = (int)Math.random() * (selector.length -1);readSelector = selector[i];readSelector.setSelected(true);selectorLock.unlock();

}return readSelector.getObject();

}throw new RuntimeException("read2Phase() call must follow

30

Page 31: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

a call to readyToGet()");}

Because synchronization points support multiple put operations, a secondphase read operation before a second phase put operation might result indifferent selected selectors. When the data is read from the operation ofthe first selector and this data satisfies the data constraint, but the data ofthe second selected selector that is retrieved for the second phase put doesnot pass the data constraint, this operation should not have been executed.Therefore, when a read operation is needed to test if a constraint is passedbefore the second phase put operation is performed, one put operation isselected and the data is read from this operation. A pointer to this specificoperation is stored and the following read operations all use the pointer tothis operation. Also the second phase put operation uses this pointer.

When the put operation times-out, the pointer is set to null and a newput operation is randomly selected when a read operation is performed.When the pointer is null and directly a second phase put operation is per-formed, this second phase put operation selects a put operation randomly.Because an operation can time-out after the second phase read operationand the connector may have passed the constraints because the data fromthe operation of the first selected selector passes the constraints, but afterthe time-out the data from another put operation is retrieved with a secondphase put and the constraint may not be passed with the data from thisoperation. Therefore, an operation with a time-out will be locked when itis selected after a second phase read operation. This operation then cannottime out and changes the state of the selector so that the second phase readoperation knows that it should time-out when the constraint is not met andthe transition is not executed. If the constraint was met and the operationis executed the time-out state is ignored.

Example

In Figure 12 on page 32 a diagram with four different write operations isshown. All operations have time-outs and the transition that is executedby the connector requires the data constraint to be true. The first writeoperation calls the put() method of the synchronization point. This syn-chronization point creates a selector for this operation and because this op-eration has a time-out, also a watchdog is created. The connector calls thereadyToPut() method of the synchronization point, and the synchronizationpoint selects one of the selectors.

31

Page 32: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 12: Possible Read2Phase operations with time-outs

32

Page 33: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

In this case there is only one selector, but in the case of multiple selectorsa pointer is set to the selected selector, this pointer ensures that only thisselector is used for the operation and not that any of the other selectors,thus operations, are interchanged and the data for the constraint is mixed.

The selector returns true to the connector and because the transition hasa data constraint, the data is first read to test if the constraint is passed ornot. This is the case, so the second part of the two phase operation is exe-cuted by calling the put2phase() method of the synchronization point. Thisunlocks the selector of the corresponding operation and the synchronizationpoint can complete the write operation.

In the second write operation, the same steps occur, but now the con-straint is false and the first part of the two phase operation is not completed.Instead of the put2phase() method, the end2phase() method is called andthe write operation is not completed. Because the component that executesthe operation is blocked during this process until the operation is completedor a time-out occurs, the component stays blocked when the constraint isfalse and the operation stays available for other transitions of the connector.

In the third operation a time-out of the component occurs during theread2phase() method of the connector. This time-out is started by thewatchdog. But because the selector and the synchronization point are lockedduring the two phase operation, this time-out cannot directly stop the ex-ecution of the operation. Fortunately the data constraint is true and theoperation is completed before the time-out can occur. After the completionof the operation, the time-out of the watchdog is ignored and the selectorand the watchdog are removed.

The final operation is also interrupted by a time-out, but because of thelocked selector and synchronization point, this time-out also has to wait.Unfortunately the constraint of the transition is not passed with the dataof this write operation, and the two phase operation is ended by calling theend2phase() method. Just like the second operation, this operation is stillavailable and therefor the time-out is executed and it stops the executionof this operation by unlocking the selector and sending false as the returnvalue of the operation to the component.

4.2.7 Terminate

A component based program is based on different components and the con-nector. Each of them operates on its own timing and operations. If a singlecomponent or if the connector is terminated, the other parts of the pro-gram will continue. If the connector is finished and terminates, also the

33

Page 34: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

components should terminate. To solve this a terminate method must beimplemented in each component. Such method is also implemented in thesynchronization point. Before the connector terminates, it calls the termi-nate method of each synchronization point. This sets the terminate booleaninside the synchronization point to true.

public void terminate() {terminated = true;

}

public boolean isTerminated() {return terminated;

}

Each component must check this boolean of each synchronization point it isconnected to inside the main method. If it is false, the component continues,else it terminates as well. If a component terminates, it can also call theterminate method of the connected synchronization points so that they no-tify the connector. The connector will then notify all other synchronizationpoints and thus the other components and the connector will also terminate.

Because the components will not continually check the termination ofthe connected synchronization points, the component will only terminatewhen it is not blocked by an operation. If the component is blocked by anoperation with a time-out, the component will terminate after the time-out.If the operation does not have a time-out, the operation will stay lockedbecause the other components already terminated and the component willnever terminate.

The synchronization points are defined in the main program and theywill only terminate when all other parts are terminated, thus only when themain program terminates. If one or more parts are not terminated, the mainloop and thus the synchronization points will not terminate. This cannot besolved by terminating the locked operations, because operations without atime-out cannot be terminated. Terminating an operation without a time-out leads to a exception and results in a different output of the program.

5 CASP

This whole research project is called CASP: Constraint Automata with Syn-chronization Points. This project started with researching the possibility touse Reo circuit models for developing model-driven software. This model is

34

Page 35: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

able to coordinate different components in a synchronous way, but to gen-erate the software more easily, requires an additional model to use Reo fordeveloping model-driven software. This additional model is the constraintautomata and Reo circuits can easily be converted to constraint automata.A template for the code generation from constraint automata consists of aloop that, with a special synchronization point, is able to coordinate thecomponents as a program. The synchronization point is the base for CASP,because all necessary methods for the coordination are implemented in thisdata structure.

This final part describes the design of the connectors, called coordina-tors in CASP, and the design of the components. Also the implementationdetails of the used models, and the implementation of CASP in the Eclipseenvironment are discussed. Finally some examples are given to show thepossibilies of this model-driven software approach.

5.1 Implementation

The parts of CASP are all implemented as an Eclipse plug in and they arebased on EMF models that are visualized with GMF. The idea is to easilycreate components with the Java wrappers and to construct coordinatorswith the Reo circuit model or the constraint automata model. New orexisting coordinators and components are then combined in the CASP modeleditor in which the components are easily connected to the coordinator likea drawing program. The model then can be used to generate the final Javaclass that initializes and starts all Java classes for the components and thecoordinators in order to make this a real multi threaded, component basedJava program.

Because all generated code is based on the most simple programmingstructures and no special Java methods and structures are used, all code caneasily be generated in any other thread supporting programming language.The real code generation is based on JIT: Java Emitting Templates so onlychanging these templates for other languages enables CASP to generateprograms in other languages based on exactly the same Reo circuits forthe coordinators and only requires language dependent wrappers for thecomponents.

5.1.1 Coordinators

In a CASP program the components are controlled by the coordinator. Thiscoordinator communicates via the synchronization points to the compo-

35

Page 36: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 13: Main flow of actions in the coordinator

36

Page 37: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 14: Sub flow of actions in the first phase

37

Page 38: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 15: Sub flow of actions in the second phase

38

Page 39: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 16: Sub flow of actions in the third phase

39

Page 40: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

nents. This communication is based on constraint automata. The statesand the transitions of the constraint automaton are simulated by the coor-dinator. In order to use a constraint automaton as a coordinator, it shouldbe modeled as a constraint automata model or converted from an existingReo circuit model to a constraint automata model. This constraint au-tomata model can then be used to generate the Java code that can be usedas coordinator software.

All information from the constraint automaton can be found in the Javacode of the coordinator, like the number and type of ports, called nodes,the transitions and the buffers. The Java code of an example coordinator isshown below. This example coordinator is based on the constraint automataof the Fibonacci example, see Figure 22 on page 58.

The constraint automaton of the Fibonacci example has three ports,stored in numberOfNodes, and four transitions. The total number of buffersis also four. The index of the transition that is currently tested for availableoperations is stored in the currentIndex. The current state of the constraintautomata is stored in the currentState. The type of ports to execute op-erations on are stored in an array of booleans, called isOutputPort. Thearray of currentActivePorts is related to the synchronization points. If asynchronization point has one or more operations waiting, the correspond-ing port in this array is true. If a synchronization point has no operationwaiting, the corresponding port in this array is false. PossibleTransitions isa two dimensional array of booleans that contains the necessary active portsneeded for each transition. The objectBuffer is an array of objects to serveas buffers. The start state and end state of each transition is stored in thestartStates and endStates array.

private final int numberOfNodes = 3;private final int numberOfTransitions = 4;private final int numberOfBuffers = 4;

private int currentIndex = 0;private int currentState = 0;

private boolean isOutputPort[] = {false, false, true};

private boolean currentActivePorts[] = {false, false, false};

private boolean possibleTransitions[][] = {{false, false, false},{true, false, false},{false, true, false},{false, false, true}};

40

Page 41: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

private Object objectBuffer[] = new Object[numberOfBuffers];

private int startStates[] = {0, 1, 2, 3};

private int endStates[] = {1, 2, 3, 1};

Finally extra information is added for the coordinator in order to workproperly, like testingTransition, this is an array where a copy of the cur-rentActivePorts is stored. This copy is used to test the current transitionfor available operations. If the currentActivePorts array is used for this pur-pose, ports of this array might change, making the tesing of operations morecomplex. The boolean possibleHit is set to true if all necessary ports havean operation for this transition available. The phaseHit variable is set totrue when all these operations are ready to start the second phase put andget operations. When this is the case the transition will finally completeand the transaction boolean is set to true. Only when this boolean is set totrue, the currentState is changed to the end state of the current transition.

For testing purposes the coordinator can be terminated when no transi-tion is possible anymore. This is done by increasing the possibleHalt variableby one if a transition cannot complete. If none of the transitions can be com-pleted this variable becomes higher than the number of transitions and thecoordinator will terminate. Normally this should not terminate the coor-dinator because it is still possible that components perform read or writeoperations.

If the coordinator or one of the components is terminated and the con-nected synchronization points are notified by the terminate method, thepossibleTerminate variable is set to true and the coordinator will notify allsynchronization points to terminate the components as well. The time-outvariables enable a global time-out mechanism to terminate the program af-ter 30 seconds of inactivity. The synchronization points that are connectedto this coordinator are stored in an array of synchronization points.

private boolean testingTransition[] = new boolean[numberOfNodes];

private boolean possibleHit = false;private boolean phaseHit = true;

private boolean transaction = false;

private int possibleHalt = 0;private boolean possibleTerminate = false;

41

Page 42: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

private int timeOut = 30000;private long lastTimeCheck;

private SyncPoint syncPoints[] = new SyncPoint[numberOfNodes];

The constraint automaton of the Fibonacci example in Figure 22 on page 58show the three ports, namely A, B and C. The four nodes and the fourtransitions in which the ports and buffers are used. In the constructor ofthe Fibonacci example coordinator these ports are passed as parameters.These parameters can be CorOut for input ports of the components andCorIn for the output ports of the components. Note that the input port ofa component is an output port, and an output port is an input port fromthe coordinators perspective. CorIn and CorOut are interfaces of the syn-chronization point class. These ports are stored as synchronization points inthe syncPoints array. The next method adds the information like the indexand the type of port to the synchronization point. The currectActivePortsarray is passed to the synchronization point to serve as an pointer to thisarray so that each synchronization point can update this when operationsare started or completed.

public ExampleCoordinator(CorOut A, CorOut B, CorIn C) {syncPoints[0] = (SyncPoint) A;syncPoints[0].setNodeInformation(0, 0, currentActivePorts);

syncPoints[1] = (SyncPoint) B;yncPoints[1].setNodeInformation(1, 0, currentActivePorts);

syncPoints[2] = (SyncPoint) C;syncPoints[2].setNodeInformation(2, 1, currentActivePorts);

}

Now all the necessary information of the constraint automaton is stored inthe coordinator and it is ready to start coordinating when all the componentsare connected. This coordination is visualized as a loop in the main diagramof Figure 13 on page 36.

First a copy of the currentActivePorts array is stored in the testingTran-sitions array. Then the availability of the necessary operations is tested, i.e.,if this is a possible transition. If this is a possible transition, in the phase1 sub diagram, each necessary operation is locked and tested if it is readyfor execution. If all necessary operations are locked and ready, the diagramreturns to the main diagram. If one of the necessary operations is not ready,the phase 1 subdiagram returns to the phase 3 subdiagram.

42

Page 43: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

In the main diagram, the data constraints for this transition are tested.These data constraints are hard-coded tests for each coordinator, if thereare no constraints or all conditions are true, the diagram enters the phase 2subdiagram, else the phase 3 subdiagram is entered. In the phase 2 subdia-gram, all operations are executed and the transition is taken. Finally, whenthe phase 2 subdiagram returns to the main diagram, the currentIndex isincreased by one so that the next transition can be tested.

If the currentIndex is bigger than the number of transition, the cur-rentIndex is reset to zero and the first transition is tested again. If theloop is stopped in the first case because not all necessary operations forthis transition are available, only the currentIndex is increased and the nexttransition is tested. Also, if the currentIndex is bigger than the number oftransition, the currentIndex is reset to zero and the first transition is testedagain.

If the loop is stopped in the phase 1 subdiagram, because all necessaryoperations are available, but not all operations are ready for execution, theoperations are still locked, these should first be unlocked, this is done in thephase 3 subdiagram by calling the end2Phase() method for each operationand after this, in the main diagram, the currentIndex is increased by one.

This is also the case if all operations are ready, but not all conditionsof the data constraint are true. The phase 3 subdiagram is entered, theoperations are unlocked, the currentIndex is increased by one and if thecurrentIndex is bigger than the number of transition, the currentIndex isreset to zero and the first transition is tested again.

The only two ways to end this loop are by terminating the coordinatorand all components by a component calling the terminate() method of a syn-chronization point. This terminate signal is passed to the coordinator andthe coordinator terminates all other components by calling the terminate()method of all other synchronization points.

The second way is a global time-out mechanism in the coordinator, ifthere are no possible transitions for a given number of (milli)seconds, theterminate() method of all synchronization points are called and the compo-nents and the coordinator terminates. If a transition is possible the globaltime-out is reset and the next transition is tested.

5.1.2 Components

The coordinator in CASP is generated automatically and is based on aconstraint automaton or a Reo circuit that is converted to a constraint au-tomaton. The components coordinated by this automaton or circuit should

43

Page 44: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

be created manually. This comes with some restrictions, but also a lot ofpossibilities. First of all a component can be written in any language andwith any programming methodology. It can be an existing program or ascript, even an on-line web service. Second, the components in a compo-nent based program don’t have to bother about the communication withother components. This is all done by the coordinator. The only inputand output a component can perform is communicated via the input andoutput ports that are given as parameters to the constructor. If the com-ponent is a non-Java program, a Java wrapper can be created that handlesall communication of the component via these input and output ports.

public class Consumer extends Thread implements Component {private ComIn comIn;private boolean stop = false;

public void run() {Object theObject = null;while (!stop) {

theObject = comIn.get();System.out.println("Consumed " + theObject);

}}

public Consumer(ComIn s) {comIn = s;

}

public void terminate(){stop = true;

}}

An example Java based component is shown above, this Consumer has itsown thread and implements Component to ensure the implementation ofmain, the terminate and the constructor methods. The run method is im-plemented as the component’s main loop. The terminate method is imple-mented to enable to stop the component when the coordinator is terminated.The constructor takes all input and output ports of the component as pa-rameters and stores them as private ports. Inside the main loop a while loopensures that the component will run until the component is terminated. Andinside this loop the component can start put and get operations to the in-put and output ports. An operation is handled by the synchronization pointwhen matched by its counterpart operation by the coordinator. Only when

44

Page 45: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

the operation is complete, the component continues with its own operations.

5.2 Eclipse

In the SEN3 group the mostly used programming environment is Eclipse. Alot of tools are already developed for this integrated development environ-ment and many more plugins and other third party software can be addedto Eclipse. Eclipse was originally developed by IBM and later given to aindependent non-profit consortium: The Eclipse Foundation. By defaultEclipse is a Java Integrated Development Environment with its own JavaDevelopment Toolkit and Java compiler. It is primarily written in Java,but users can extend its capabilities by installing plug-ins written for theEclipse software framework, such as development toolkits for other program-ming languages.

5.2.1 EMF

To create the models for the Reo circuit and the constraint automata inEclipse there is the Java framework and code generation facility EMF, theEclipse Modeling Framework. This framework helps to create model basedefficient, correct and easily customizable Java code. The first step is tocreate a model definition, this definition can be created using a XML ortext editor, but can also be exported from several modeling tools. Whenthe model is defined, this definition is used to generate a corresponding setof Java classes. These Java classes can be used to generate, save, view andedit instances of your own defined model. This model can also easily beused as a plug-in for Eclipse itself [9].

5.2.2 GMF

The Java classes that are generated with EMF make it possible to createnew instances of our model in Eclipse, but these instances are text basedinstances. To make nice graphical instances there is the Graphical EditingFramework, GEF. This framework can create rich graphical editors fromexisting application models. EMF and GEF are combined into GMF, theGraphical Modeling Framework. Several models are already created withthis framework, like a model to build Reo circuits and a model to buildconstraint automata. The combination of EMF and GEF leads to a powerfultool to create all kinds of models with graphical user interfaces.

45

Page 46: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

5.2.3 Reo circuits model

Within the SEN3 group several models are already implemented with GMF.One of these models is a model to create Reo circuits. Within a graphicalenvironment it is possible to draw components and different kinds of stan-dard channels. These channels are synchronous channels, lossy synchronouschannels, FIFO, lossy FIFO, drains and spouts. With a special type of nodechannels can be connected together to create mergers and replicators. Com-ponents are simulated with writers and readers. Both can read or write acertain number of times. A reader or writer can be connected to a node withan IO link. The created connectors can be saved and used as a new channelinside another model. When the Reo circuit is finished an animation showsthe possible data flow for this circuit.

5.2.4 Constraint automata model

Just like the model for the Reo circuit, there is also a model for creatingconstraint automata. A constraint automaton in this model has its ownname, ports and domain. The ports are the variables that are necessary fora transition and the domain defines the possible values of these variables.Then there are the states, including a start state and the transitions betweenthe states. Each transition has a label with the necessary ports and a dataconstraint. In a single model multiple constraint automata can be created.These automata can then automatically combined as a single automaton bycalculating the product of these automata. To convert a Reo circuit to aconstraint automaton some changes are made in the original model for theconstraint automata. For example, the original model did not support theusage of buffers in the data constrains and the type of ports could not bestored in this model. Due to these changes this necessary information of theReo circuit can be stored in the constraint automaton.

Ports

The model for the Reo circuit has readers and writers for the components.The constraint automata has ports that can do the same. By looking atthe Reo circuit, we extract the node types (source, sink or mixed) andshow the source and sink nodes as input and output ports in the constraintautomaton.

46

Page 47: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Domain

In the model for the Reo circuit there is no definition for the type of datathat is moved over the channels. Of course it should be possible to move anytype of data over a channel. But in the model for the constraint automatathe only possible data type where integers. This was easier for checking theconstraints in the transitions. By adding strings and variables to the domainmore types must be checked and by extending not only the domain, but alsothe constraints, even Java code can be checked and used in the constraints.

Buffers

Besides the extension of the domain and the constraint also buffers shouldbe added to the constraints of the automata. This enables the possibilityto simulate the FIFO channels from the Reo circuit model in the constraintautomata model. For this each state got its own list of buffers and thesecan be addressed from within a transition. Two new variables are availablein the transitions $s and $t. The $s is used to read from a buffer in thesource state and $t is used to write into a buffer in the target state. To usea buffer in the constraint the variable for the target or source state is usedand after this a dot is added continued by the name of the buffer. In thenext example the data from the oldBuffer in the source state is moved intothe newBuffer in the target state.

$s.oldBuffer == $t.newBuffer

The buffers that are defined in the constraint automata model are checkedduring modeling. For example, the buffers are checked if they are used ornot, if not they are deleted. Because each buffer requires extra memory itis important to remove the unused buffers. Besides this optimization thefilling and emptying of the buffers is checked. Each connection to a buffershould fill the buffer in the constraint and each connection from the buffercan read the buffer in the constraint.

Parser

To make sure that all this information is typed correctly into the constraintof the transition in the constraint automata model, a constraint parser isused. The parser is generated by ANTLR, ANother Tool for LanguageRecognition that uses a formal grammar to create a Java class that canrecognize sentences that belong to the language of the specific grammar.

47

Page 48: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

The constraint consists of clauses, these clauses have equations of atomsand these atoms can be identifiers, integers or buffers.

constraint: (clause (OR^ clause)*) |;

clause: (LPAREN! equation (AND^ equation)* RPAREN!) |(equation (AND^ equation)*);

equation: (atom EQUAL^ atom);

atom: (IDENT | INT | buffer);

buffer: ST DOT! IDENT;

5.3 CASP editor

When a coordinator is generated and the components are created, all partsshould be combined in a new CASP program. This is done in the CASPeditor. In this editor each CASP program is build with its own new CASPmodel. This model is created the same way as a new Reo circuit or con-straint automata model in the Eclipse environment. With a small toolboxnew components and a coordinator can be added to the model, these canbe connected together and from this model a new Java program can begenerated.

When a component is inserted into the CASP model editor a yellowbox appears with a certain number of dots. These dots are the input andoutput ports that are defined as the parameters of the constructor of theJava code of this component. These ports should be connected to the correctcomplementary ports of the coordinator.

When a coordinator is inserted into the CASP model editor, a blue boxappears with a certain number of dots. These dots are the input and outputports that are defined in the constraint automata and these ports should beconnected to the correct complementary ports of the correct components.

5.3.1 Drag-n-Drop

The models, components and coordinators written in Java can easily becreated in the Eclipse environment. This environment supports all the plugins needed for the CASP model and the code generation. If a new CASPmodel is started in Eclipse, the coordinators and components can be drag-n-dropped from the package explorer into the CASP model editor. The editor

48

Page 49: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

investigates the source of the dropped file and automatically creates a bluebox for a dropped coordinator and a yellow box for a dropped component.After this the constructor of the coordinator or the compoment is checkedfor the number of input and output ports and these ports are automaticallycreated as dots and added to the belonging box. It is also possible to definea component or coordinator with the correct number and type of ports byhand with the toolbox of the CASP model editor.

5.3.2 Connections

If a coordinator and a number of components are added to the CASP modeleditor the last step is to connect all corresponding ports. By hovering overthe coordinator and components information is given about this coordinatorand the components. More detailed information about the input and outputports of the coordinator and the components is given when hovering overthese ports. This information includes the name of the port, the connectionstate, the component or coordinator it belongs to and the type of port. Byclicking on a port a wire is connected and this wire can be dragged to anotherport, just like drawing lines in a drawing program. The only connection thatcan be created connect an input port of the coordinator to an output portof a component, an output port of the coordinator to an input port af acomponent and the other way around. A port can only be connected to asingle other complementary port.

5.3.3 Checks

To preserve a stable and correct CASP model some parts of the model areconstantly checked during modeling. This starts by adding a componentor coordinator. Each component or coordinator has several parameters forthe constructor. These parameters are used to generate the input or outputports in the graphical CASP model editor. If there are extra parametersthat are not used as input or output ports in the implementation of the con-structor of a component or the coordinator the model editor gives a warning.This warning states that this unknown parameter should be defined and ini-tialized manually by the user. When the CASP model is ready, but not allports are connected the CASP editor cannot generate the source code for theprogram and the ports that are not connected must be connected correctlybefore the code generation can continue. Sometimes multiple instances ofthe same component are used. This is no problem, but the generated codecannot use the same component names. Therefore each component name

49

Page 50: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 17: Generated package with CASP.jar library

has its own index. This way it is no problem to have multiple instances ofthe same component.

5.4 Code Generation

After connecting all the ports of the components and the coordinator it isfinally time to invoke the code generator. This is done by right clicking onthe model and selecting the generation code option, then select CASP codegenerator.

A window is shown where the project, package and class names can begiven. An option box is selected to indicate that the main loop should begenerated and also there is the possibility to select a different location tostore the generated code. If there are warnings or errors in this CASP model,then these are also shown in this new window.

After selecting finish a new project is created in the package explorer. Inthis project the given package is created with a Java class and some libraries.Most of these libraries are standard Java libraries for the project, but thereis also a CASP specific library called CASP.jar. The CASP.jar contains theJava interfaces for the components and the coordinator. It contains the Javaclasses for the synchronization point, the semaphores, the selector and thewatchdog and finally the interfaces for the input and output ports for thecoordinator and the components.

The generated Java code consists of imports of all necessary librariesand the class files of the components and the coordinator. After this theJava class of the program is defined together with the main method. This

50

Page 51: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 18: Time Temperature REO circuit [3]

main method defines and initializes the synchronization points for all theconnections between the components and the coordinator. For each compo-nent and the coordinator these synchronization points are accessible throughJava interfaces to these synchronization points. The interfaces are definednext. Finally the components and the coordinator are defined and the in-terfaces to the synchronization points are given to them as parameters. Acall to the start method of the components and coordinator are added andthe code is finished.

6 Examples

To show the possibilities and the easy use of the CASP model a numberof interesting examples are added. These examples start with simple com-ponents and not too complex coordinators, but with the last example, thepower of the coordinator and the flexibility of the CASP model are shown.In this section only the models are shown and the theory is explained, butall the source code of the examples is available in the appendix.

6.1 Time-Temperature

The first simple example is the Time-Temperature example. This is a knownexample from the big electronic billboards above buildings that continuouslyshow the time followed by the temperature and so on, see [3]. The systemconsists of three components and a coordinator. The components are the

51

Page 52: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

clock to generate the time, the thermometer to generate the temperatureand the display to show the data. Each generator has a single output andthe display has only one input.

6.1.1 Components

The thermometer and the clock component are the most basic componentspossible, with only a single output port to put data to. The thermometercomponent puts the current temperature and the clock component puts thecurrent time on the output port. The display component has only one input,the data that it gets from this input is shown on the screen.

The components have the same skeleton that consists of the packagename, the synchronization point and components library and the publicclass that extends Thread and implement Component. This public classhas a private output port and a boolean to stop the main loop. The runmethod contains this main loop and inside this loop a single put operationis executed. Before this operation the thread sleeps an amount of time toslow down the execution of the component. The put operation is performedwithout a time-out, thus the return value of the operation should alwaysbe true. Finally the output port is tested for termination, in this case thecomponent also terminates by calling the terminate method. Finally theparameter in the constructor is used to connect the output port.

package cwi.components;

import cwi.casp.syncpoint.*;import cwi.casp.components.*;

public class ClockComponent extends Thread implements Component {private ComOut comOut;private boolean stop = false;

public void run() {Object theObject = null;while (!stop) {

try{Thread.sleep((long)(2000));

}catch (InterruptedException e) {

// ignore}theObject = new String("Something");if(comOut.put(theObject))

52

Page 53: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

System.out.println("Put: " + theObject);else

System.out.println("Impossible,no time out used!");

if(comOut.isTerminated())terminate();

}}

public ClockComponent(ComOut clockOutput) {comOut = clockOutput;

}

public void terminate() {stop = true;

}}

These lines of programming code are only a skeleton. Both the thermometerand the clock component use this same skeleton, but they put differentdata to the output port. The skeleton can also be used for the displaycomponent, but then the part where the data is put should be replaced bysome operations and tests to get the data from the input port.

theObject = comIn.get();if (theObject instanceof String)

System.out.println("Print to screen: " + (String)theObject);else if (theObject instanceof Boolean)

System.out.println("TimeOut: " + (Boolean)theObject);if(comIn.isTerminated())

terminate();

6.1.2 Coordinator

The coordination of the components is defined by the Reo circuit. If the Reocircuit simply connects both output ports to the input port of the displaycomponent via a node, the data displayed on the screen is undefined. Thenode that combines the data from the two output ports nondeterministicallyselects the data of one of the output ports. The Reo circuit to show the datain a sequential and timed order contains four black boxes. Three of themare the components and one is a connector called a sequencer. The smallrounded boxes are variables. The sequencer and the variables are genericcoordinators and these can be used in any coordinator. Together with theReo channels the data from the two output ports are stored in the variables.

53

Page 54: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 19: Constraint Automata for Time Temperature REO circuit

Whenever new data comes out of an output port, the data in the variableis replaces by the newest data. The sequencer has its own operations andtiming, but because the ports of the sequencer are synchronized with thedata that flows to the input port of the display, this sequencer coordinatesthe whole Reo circuit. With an interval that depends on the read speed ofthe display component, only one of the two variables can pass its contentto the input port of the display. If the data is generated faster or slowerthan it is shown on the display, the older data in the variable is overwrittenor reread. All components operate on their own time and this coordinatorensures the correct execution of the Reo circuit.

To generate the Java code for this coordinator, this Reo circuit mustbe converted to a constraint automaton. This constraint automata can becreated automatically from the Reo circuit but for this example a simpli-fied version is made manually. The main parts of the coordinator are thesequencer and the variables. The sequencer consists of a variable that ischanged from zero to one and back. Depending on the value of this variablethe constraints are true or false and only one transition is enabled. Thistransition connects the correct port of a component to the port of the dis-

54

Page 55: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 20: Time Temperature CASP Model

play and changes the value of the variable so that the other components’port is connected the next time. The variables in the Reo circuit are im-plemented as buffers. These buffers are overwritten every time new data isgenerated. There is no concept of time in this constraint automaton, thisdepends on the timing of the components.

6.1.3 CASP model

Now that the components and the coordinator are ready the CASP modelcan be created to connect everything together and to automatically generatethe Java code that can be compiled and executed. This is done in Eclipse.In Eclipse a new CASP model can be created by selecting the menu optionNew and then select Other. In the pop up diagram in the CASP categorya new CASP diagram can be selected. In the new CASP model the coor-dinator and the components are dragged from the file tree inside the modeleditor. A blue box appears for the coordinator and three yellow boxes forthe components. The light gray dots for the output ports and the darkerdots for the input ports are automatically generated and aligned inside thecorresponding component or coordinator. By hovering over these dots thetype and name of the port can be determined and now these dots should sim-ply be connected to the corresponding dots. When all the dots are correctlyconnected the CASP model is ready and the Java code can be generated au-tomatically. The generated Java classes can be compiled and the resultingprogram shows the expected output on execution.

55

Page 56: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 21: Fibonacci REO circuit [3]

6.2 Fibonacci

A more advanced example but with a simpler looking CASP model is createdwith the CASP implementation of the Fibonacci series. As discussed in [3]there is only one component and a coordinator needed to create a Reo circuitthat can calculate the Fibonacci series.

6.2.1 Component

For this example there is a sum component with two input ports and oneoutput port. The values of the input ports A and B are added together andthe result is put on the output port C. The value that is put to port C canbe connected to a display object, but to simplify this example the value isprinted on the screen by the component itself. In the Reo circuit, there arethree buffers. The value from the first buffer is send to the second bufferand to input port B. The value from the second buffer is send to the thirdbuffer and the value from the third buffer is put to input port A. The valuesof ports A and B are processed by the sum component and put to outputport C. This value is then printed and stored into the first buffer.

public class Sum extends Thread implements Component {private ComIn a;private ComIn b;private ComOut c;private boolean stop = false;

public void run() {int valueA = 0;int valueB = 0;int valueC = 0;while (!stop) {

56

Page 57: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

valueA = Integer.parseInt(a.get().toString());valueB = Integer.parseInt(b.get().toString());valueC = valueA + valueB;if(valueC < 0) {

terminate();} else {

c.put(valueC);System.out.println("Output on C: " + valueC);

}if(a.isTerminated() || b.isTerminated() || c.isTerminated())

terminate();}

}

public Sum(ComIn a, ComIn b, ComOut c) {this.a = a;this.b = b;this.c = c;

}

public void terminate(){a.terminate();b.terminate();c.terminate();stop = true;

}}

The main method run shows the initialization of the three integers for thevalues of the three ports. In the main loop the values of input ports A andB are retrieved by a call to the get() method and these values are parsed asintegers. The sum of the two integers is stored in valueC. Because there isno possibility to stop the program, the value of valueC is tested. If this valueis smaller than zero, probably the maximum value of an integer is reachedand the value is negative. This triggers the component to terminate. Ifthis is not the case, the value of valueC is printed onto the screen and thesynchronization points connected to the three ports are tested for termina-tion. If one of these synchronization points is terminated, the componentalso terminates. The constructor of the sum class has three parameters. Foreach private input or output port there is a parameter to connect it to thesynchronization points of the coordinator. The terminate method is calledto terminate all connected synchronization points and to stop the main loop.

57

Page 58: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 22: Constraint Automata for the Fibonacci Reo circuit

6.2.2 Coordinator

The constraint automaton to represent this Reo circuit is also manuallybuilt. Because the sum component does not use separate threads the con-straint automaton has separate sequential transitions in order to preventdead-lock. The buffers are defined as x, y and t. In the first transition, thebuffers are initialized with the first Fibonacci results 0 and 1. The currentresult is stored into buffer t and the data of the other buffers are passedto the input ports A and B of the sum component. After the operation ofthe sum component, the next result is stored into buffer y and the currentresult is stored into buffer x. The constraint automaton model is build inthe Eclipse environment. By right clicking on the model the code genera-tion option can be selected to automatically generate the Java code for thecoordinator from the constraint automaton model. The Java code consistsof a new project in the file tree of the Eclipse environment. This projectcontains the necessary classes and libraries.

6.2.3 CASP model

Now that the component and the coordinator are ready, the CASP modelcan be created to connect everything together and to automatically generate

58

Page 59: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 23: Fibonacci CASP model

the Java code that can be compiled and executed. This is also done in theEclipse environment. In the new menu option, select other and the CASPcategory in the pop up window. In the new CASP model the Java classesof the coordinator and the component are dragged from the file tree insidethe model editor. A blue box appears for the coordinator and a yellow boxfor the component. The light gray dots for the output ports and the darkerdots for the input ports are automatically generated and aligned inside thecorresponding component or coordinator. By hovering over these dots thefunction and the name of each port can be determined and now these dotsshould simply be connected to their corresponding dots.

When all the dots are correctly connected the CASP model is ready andthe Java code can be generated automatically. This is done by right clickingin the CASP model and selecting the code generation option. The details ofthe new project can be given in the wizard and the code can be generated.The output is a new project in the file tree of the Eclipse environment.This project contains the necessary classes and libraries for the Fibonacciprogram. The generated Java classes can be compiled and the resultingprogram shows the expected output on execution.

6.3 Dining philosophers

The final example consists of three versions of the dining philosophers. Thefirst version is the standard version where dead-locks can occur. The secondversion is slightly modified so that dead-locks cannot occur, and the finalversion is the first version but with time-outs so that dead-locks also shouldnot occur [2].

The philosophers can have several states. The first state is waiting orthinking and nothing happens. After a while a philosopher likes to eat and

59

Page 60: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 24: A Chopstick component as a Reo circuit [2]

Figure 25: Constraint Automata for the Dining Philosophers REO circuit

therefore it needs two chopsticks. The philosopher starts by taking the leftchopstick and on success, it tries to take the right one, but because thechopsticks are shared by the neighbor philosophers, a chopstick sometimesis already in use by another philosopher and the philosopher has to waituntil this other philosopher stops using the chopstick. When a philosopheris done eating it releases the left chopstick first and then the right chopstick.

6.3.1 Components

The dining philosophers example consists of several instances of two com-ponents: the philosopher component and the chopstick component. Aninstance of a chopstick can be in use by an instance of a philosopher oris free. An instance of a chopstick can be used by only one instance of aphilosopher at a time. An instance of a philosopher requires two output

60

Page 61: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

ports one for each of the two chopsticks. But because there is an instance ofa chopstick on the left and on the right side of an instance of a philosopher,the philosopher component needs four output ports in total. The Chopstickcomponent only needs a buffer to remember if it is used or not. And it needsa mechanism to connect to both ports to fill the buffer and to both ports toempty the buffer by it two neighboring philosophers.

Loop:- Sleep before starting- Try to take the left chopstick- Wait a moment- If is has the left chopstick, try to get the right chopstick- If it has both chopsticks, eat for a while- If it has or it hasn’t the chopsticks, wait before release- As long as it has the right chopstick, try to release it- Wait before releasing the left chopstick- As long as it has the left chopstick, try to release itEnd loop

The philosophers do the same steps over and over again. Some pauses areadded to slow down the process and to enable more interaction between thephilosophers via the chopsticks. The philosopher component consists of amain loop in which it attempts to get both the left and the right chopstick.The philosopher starts with the left chopstick, if this succeeds, it tries theright chopstick. If the philosopher has both chopsticks, it will eat for awhile. After eating the right chopstick is released, then, and also after notsucceeding in taking the right chopstick the left chopstick is released.

The chopstick component is so small that is it easier to implement theseinstances into the coordinator. The buffer in the component is the same asa buffer in a Reo circuit and the mechanism to connect multiple ports tothis buffer can easily be replaced by a merger.

6.3.2 Coordinator

The coordination of this example is the same for all the three versions ofthe dining philosophers. First the Reo circuit for the first version of thedining philosophers with the possible dead-lock is built. This Reo circuitalso contains the extra buffers and mergers for the chopstick components.Both channels to start using this chopstick are connected with a merger onone side of the chopstick. And both channels to stop using this chopstickare connected with a merger on the other side. Even if both philosopherswant to start to use this chopstick at the same time, the merger will nonde-terministically select one of them.

61

Page 62: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 26: Dining Philosophers REO circuit with possible dead-locks [2]

We use here a constraint automaton for this Reo circuit that is manuallycreated, and generate its Java code automatically. This constraint automa-ton has only two states. The first one is used to set all the values of thebuffers in the chopstick instances to 0. This means that the chopsticks arenot used at all. From the second state many of transitions are possible.Each philosopher can start using or stop using one of the two chopsticks.If there is a put operation request on one of these ports, the buffer of thechopstick should contain the correct value. The value 0 if the philosopheris using the chopstick, and the value 1 if the philosopher is not using thechopstick. If the value for the operation is correct, the buffer value of thechopstick is changed and the philosopher can continue with the next step.

6.3.3 With dead-locks

The CASP model for the first version of this example contains only the bluebox for the coordinator including all instances of the chopsticks and fouryellow boxes for the four instances of the philosophers. Because there arefour components and many ports, connecting all these ports can be a bitdifficult. Therefor, it is important to give the ports of the components andthe instances clear names so that their function and properties are easy to

62

Page 63: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 27: Dining Philosophers CASP model with possible dead-locks

distinguish from those of other ports. This information is shown when themouse hovers above a port. After connecting all the ports correctly the Javaclasses can be generated automatically and the first version can be executed.Depending on the timing of the components, the dead-lock occurs once ina while when all philosophers take their left chopsticks and taking the rightchopstick in not possible for anyone of them anymore, because there are nomore free chopsticks left. The program hangs and nothing else happens.

6.3.4 Without dead-locks

To make sure that in the second version of the program a dead-lock cannotoccur the Reo circuit has to change a bit. The components and the coordi-nator stay the same, only the connections of one of the philosophers to itschopsticks are flipped. For this philosopher the pick and release channelsof the left and right chopsticks are interchanged. In the Reo circuit it isclear that the channels are changed. Unfortunately because of the numberof connections to the coordinator, this is not really clear in the CASP model.However, the changes are visible by comparing the connections from the up-per left philosopher to the coordinator. Executing the Java code generatedfor this connector with the same philosopher components, no dead-locks oc-cur anymore. This is only due to the small changes of the connections tothe coordinator.

When the philosophers start to eat by taking the chopstick on their leftside, one philosopher actually starts by taking the chopstick on the rightside. The philosophers now do not compete for all the chopsticks as in the

63

Page 64: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 28: Dining Philosophers Reo circuit without possible dead-locks [2]

first example, but only for three of them. This ensures that at least onechopstick will remain free and at least one philosopher is able to take twochopsticks and can start eating.

6.3.5 Dead-locks solved with time-outs

Another solution for these dead-locks can be implemented without changingthe CASP model, but by introducing time-outs in the components. An extravariable is added to the philosopher component and in order to guaranteedifferent timing per philosopher instance this variable is also added to theconstructor of the philosopher component class. When the old philosophercomponents are replaced by this new component with the time-out variable,the CASP model editor does not recognize this new parameter in the con-structor and a warning is given that this variable should be defined andinitialized manually after code generation. Now this extra time-out variablemust be added to all put operations of the component. After generating allJava code and after compiling these classes this third version can be exe-cuted. The result is the same as the first version of this example, exceptwhen a dead-lock occurs the time-out of the operations make it possible fora component to retract an operation. If a philosopher has one chopstick but

64

Page 65: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

Figure 29: Dining Philosophers CASP model without possible dead-locks

it takes too long to get the other chopstick, the operation for the secondchopstick can be retracted. After retraction the first chopstick is releasedand another philosopher is capable of taking this chopstick and can start toeat. After eating this philosopher releases the chopsticks and other philoso-phers can take them. If necessary the components retract their operationanytime it takes too long to get a chopstick. It is important to note that aphilosopher starts by taking the left chopstick and can only start taking theright chopstick when this philosopher has already obtained the left one.

7 Correlated work

During my research several other projects where interested in the possi-bilities of CASP. For example to coordinate web services or to coordinateseveral different types of media. In this section there is some extra informa-tion about one of these projects and some additional information about theCASP project.

7.1 Webservices

A realistic approach to service oriented computing on the web must em-brace service heterogeneity as a first class concern, instead of relegating itto a mere implementation detail. Mash ups already succeed in adopting adata-centric approach to service composition, but situational applicationsbased on Reo (SABRE) is an attempt to have the best of both worlds by

65

Page 66: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

marrying formal service oriented computing with the data-driven approachof mash ups. The Java code for coordinating the services with SABRE isautomatically generated by CASP [6].

7.2 Other

After the CASP project some changes were made to correlated work. Forexample the constraint automata model is evolved into the extendable au-tomata with many extra functionalities for validation and model checking.All necessary information for the coordinator code generation is nicely inte-grated and extra additions like costs of transitions can be added easily. Alsothe model for the Reo circuits is updated and extendable automata can nowbe generated automatically from a Reo circuit model.

8 Conclusion and Future development

The information about the CASP project and the given examples hopefullyshow that Reo circuits converted to constraint automata can be automat-ically converted to Java classes that can coordinate components. In com-bination with synchronization points the CASP model is strong enough todesign complex multi threaded Java programs based on Reo circuits.

Currently, the data that is communicated between the components con-sists only of pointers. Depending on the type of application, it can bepreferable to not only move the pointers with put and get operations, butto really move the data from one component to another. For example, if amulti media project uses a CASP model to coordinate large audio and videofiles of multiple gigabytes it is not preferable to move all this data around.Pointers to the files in the memory or on a harddisk should be sufficient. Butif the components are shared over multiple cores or even multiple remotesystems are used, these pointers are not available on each location and thedata must be moved to the component on the other core or system in orderto make the program work.

Often channels in Reo circuits are used only to synchronize other chan-nels or components. This happens, for instance, when data items are movedvia channels into a synchronous drain channel. In such cases the type ofdata or its size is not important. A single bit should be enough to synchro-nize the channels or components. Further research can be done on thesetypes synchronization in order to find out when it is necessary to replicate

66

Page 67: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

all the data for each channel or when a single bit is sufficient to execute thegenerated program correctly.

Currently all the code that is generated in the CASP project is Javacode. But because of the rather simple implementations of the synchro-nization points and the semaphores, these parts can easily be rewritten inother languages. Also the generated code does not contain specific Java ob-jects and constructions, all of this code can also easily be converted to otherlanguages. The code generation works with templates, if these templatesare translated to other programming languages, the whole CASP model canbe used to create coordinators and working programs in all object orientedprogramming languages that support threads. This feature and extensibil-ity makes CASP a strong and stable base for future development for allprogramming languages.

67

Page 68: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

A Example code

A.1 Time-Temperature

A.1.1 Clock component

package cwi.components;

import java.util.Calendar;import java.util.Date;

import cwi.casp.*;

public class ClockComponent extends Thread implements Component {private ComOut comOut;private boolean stop = false;

public void run() {Object theObject = null;while (!stop) {

try{Thread.sleep((long)(2000));

}catch (InterruptedException e) {

// ignore}Calendar calendar = Calendar.getInstance();Date time = cal.getTime();theObject = new String(time.toString());if(comOut.put(theObject))

System.out.println("Message: " + theObject +" is put on the outport");

elseSystem.out.println("Impossible, no time out used!");

if(comOut.isTerminated())terminate();

}}

public ClockComponent(ComOut clockOutput) {comOut = clockOutput;

}

public void terminate() {stop = true;

68

Page 69: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

}}

A.1.2 Display component

package cwi.components;

import cwi.casp.*;

public class DisplayComponent extends Thread implements Component {private ComIn comIn;private boolean stop = false;

public void run() {Object theObject = null;while (!stop) {

try{Thread.sleep((long)(5000));

}catch (InterruptedException e) {

// ignore}theObject = comIn.get();if (theObject instanceof String)

System.out.println("Display: " + (String)theObject);else if (theObject instanceof Boolean)

System.out.println("TimeOut: " + (Boolean)theObject);if(comIn.isTerminated())

terminate();}

}

public DisplayComponent(ComIn s1) {comIn = s1;

}

public void terminate(){stop = true;

}}

A.1.3 Generated CASP code

package thermoclock;

69

Page 70: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

import cwi.casp.*;import cwi.components.*;import cwi.coordinators.*;

public class Thermoclock {

public static void main(String[] args) {/*** Using the coordinator:** Create a Synchronization point for each node:*/

SyncPoint syncPoint0 = new SyncPoint(); // outport for node ClockSyncPoint syncPoint1 = new SyncPoint(); // outport for node ThermoSyncPoint syncPoint2 = new SyncPoint(); // inport for node Display

/*** Create interfaces for the components:*/

ComIn comInPortDisplay = syncPoint2;ComOut comOutPortClock = syncPoint0;ComOut comOutPortThermo = syncPoint1;

/*** Create interfaces for the coordinator:*/

CorOut corOutPortDisplay = syncPoint2;CorIn corInPortClock = syncPoint0;CorIn corInPortThermo = syncPoint1;

/*** Create components with inputs and outputs:*/

ClockComponent com0_ClockComponent =new ClockComponent(comOutPortClock);

ThermoComponent com1_ThermoComponent =new ThermoComponent(comOutPortThermo);

DisplayComponent com2_DisplayComponent =new DisplayComponent(comInPortDisplay);

/*** Create the coordinator with inputs and outputs:*/

ThermoClockCoordinator coordinator =new ThermoClockCoordinator(corInPortClock, corInPortThermo,

corOutPortDisplay);/*** Start the coordinator and the components:*/

70

Page 71: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

com0_ClockComponent.start();com1_ThermoComponent.start();com2_DisplayComponent.start();

coordinator.start();}

}

A.2 Fibonacci

A.2.1 Sum component

package cwi.components;

import cwi.casp.*;

public class Sum extends Thread implements Component {private ComIn a;private ComIn b;private ComOut c;private boolean stop = false;

public void run() {int valueA = 0;int valueB = 0;int valueC = 0;while (!stop) {

valueA = Integer.parseInt(a.get().toString());valueB = Integer.parseInt(b.get().toString());valueC = valueA + valueB;if(valueC < 0) {

terminate();} else {

c.put(valueC);System.out.println("Output on C: " + valueC);

}if(a.isTerminated() ||

b.isTerminated() ||c.isTerminated())terminate();

}}

public Sum(ComIn a, ComIn b, ComOut c) {this.a = a;

71

Page 72: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

this.b = b;this.c = c;

}

public void terminate(){a.terminate();b.terminate();c.terminate();stop = true;

}}

A.2.2 Generated CASP code

package fibonacciPrograms;

import cwi.casp.*;import cwi.coordinators.*;import cwi.components.*;

public class FibonacciProgram {

public static void main(String[] args) {/*** Using the coordinator:** Create a Synchronization point for each node:*/

SyncPoint syncPoint2 = new SyncPoint(); // outport for node CSyncPoint syncPoint0 = new SyncPoint(); // inport for node ASyncPoint syncPoint1 = new SyncPoint(); // inport for node B

/*** Create interfaces for the components:*/

ComIn comInPortA = syncPoint0;ComIn comInPortB = syncPoint1;ComOut comOutPortC = syncPoint2;

/*** Create interfaces for the coordinator:*/

CorOut corOutPortA = syncPoint0;CorOut corOutPortB = syncPoint1;CorIn corInPortC = syncPoint2;

/*** Create components with inputs and outputs:

72

Page 73: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

*/Sum com0_Sum = new Sum(comInPortA, comInPortB, comOutPortC);

/*** Create the coordinator with inputs and outputs:*/

Fibonacci coordinator = new Fibonacci(corOutPortA, corOutPortB,corInPortC);

/*** Start the coordinator and the components:*/

com0_Sum.start();

coordinator.start();}

}

A.3 Dining philosophers

A.3.1 Philosopher component

package cwi.components;

import cwi.casp.*;

public class Philosopher extends Thread implements Component {private ComOut leftTake;private ComOut leftLeave;private ComOut rightTake;private ComOut rightLeave;private int waitTime = 0;private int timeOut = 0;private String name = "";private boolean hasLeft = false;private boolean hasRight = false;private boolean stop = false;

public void run() {Object theObject = null;while (!stop) {

// wait before startingtry{

Thread.sleep((long)(waitTime));}catch (InterruptedException e) {

// ignore

73

Page 74: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

}

// object only used to send somethingtheObject = new Boolean(true);

// try to take the left chopstickif(leftTake.put(theObject, timeOut)) {

hasLeft = true;System.out.println("Message: " + name +

" has left chopstick");} else {

hasLeft = false;System.out.println("Message: " + name +

" has a time-out on left chopstick");}

// wait a momenttry{

Thread.sleep((long)(waitTime));}catch (InterruptedException e) {

// ignore}

// if is has the left chopstick, try to get the right chopstickif(hasLeft) {

if(rightTake.put(theObject, timeOut)) {hasRight = true;System.out.println("Message: " + name +

" has right chopstick");} else {

hasRight = false;System.out.println("Message: " + name +

" has a time-out on right chopstick");}

}

// if it has both chopsticks, eat for a whileif(hasLeft && hasRight) {

System.out.println("Message: " + name + " is eating");try{

Thread.sleep((long)(waitTime));}catch (InterruptedException e) {

// ignore

74

Page 75: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

}}

// if it has or is hasn’t the chopsticks, wait before releasetry{

Thread.sleep((long)(waitTime));}catch (InterruptedException e) {

// ignore}

// as long as it has the left chopstick, try to release itwhile (hasLeft) {

if(leftLeave.put(theObject, timeOut)) {hasLeft = false;System.out.println("Message: " + name +

" released left chopstick");} else {

hasLeft = true;System.out.println("Message: " + name +

" has a time-out on releasing" +" left chopstick");

}}

// wait before releasing the right chopsticktry{

Thread.sleep((long)(waitTime));}catch (InterruptedException e) {

// ignore}

// as long as it has the right chopstick, try to release itwhile (hasRight) {

if(rightLeave.put(theObject, timeOut)) {hasRight = false;System.out.println("Message: " + name +

" released right chopstick");} else {

hasRight = true;System.out.println("Message: " + name +

" has a time-out on releasing" +" right chopstick");

}

75

Page 76: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

}

// check if a syncpoint is terminatedif(leftTake.isTerminated() || leftLeave.isTerminated() ||

rightTake.isTerminated() || rightLeave.isTerminated())terminate();

}}

// constructor with syncpoints, WaitTime, TimeOut and Namepublic Philosopher(ComOut lt, ComOut ll, ComOut rt, ComOut rl,

int wt, int to, String nm) {leftTake = lt;leftLeave = ll;rightTake = rt;rightLeave = rl;waitTime = wt;timeOut = to;name = nm;

}

public void terminate() {stop = true;

}}

A.3.2 Generated CASP code with dead-locks

package chopStickPrograms;

import cwi.casp.*;import cwi.coordinators.*;import cwi.components.*;

public class ChopStickProgram {

public static void main(String[] args) {/*** Using the coordinator:** Create a Synchronization point for each node:*/

SyncPoint syncPoint0 = new SyncPoint(); // outport for node p1llSyncPoint syncPoint1 = new SyncPoint(); // outport for node p1ltSyncPoint syncPoint2 = new SyncPoint(); // outport for node p1rl

76

Page 77: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

SyncPoint syncPoint3 = new SyncPoint(); // outport for node p1rtSyncPoint syncPoint4 = new SyncPoint(); // outport for node p2llSyncPoint syncPoint5 = new SyncPoint(); // outport for node p2ltSyncPoint syncPoint6 = new SyncPoint(); // outport for node p2rlSyncPoint syncPoint7 = new SyncPoint(); // outport for node p2rtSyncPoint syncPoint8 = new SyncPoint(); // outport for node p3llSyncPoint syncPoint9 = new SyncPoint(); // outport for node p3ltSyncPoint syncPoint10 = new SyncPoint(); // outport for node p3rlSyncPoint syncPoint11 = new SyncPoint(); // outport for node p3rtSyncPoint syncPoint12 = new SyncPoint(); // outport for node p4llSyncPoint syncPoint13 = new SyncPoint(); // outport for node p4ltSyncPoint syncPoint14 = new SyncPoint(); // outport for node p4rlSyncPoint syncPoint15 = new SyncPoint(); // outport for node p4rt

/*** Create interfaces for the components:*/

ComOut comOutPortp1lt = syncPoint1;ComOut comOutPortp1ll = syncPoint0;ComOut comOutPortp1rt = syncPoint3;ComOut comOutPortp1rl = syncPoint2;ComOut comOutPortp4lt = syncPoint13;ComOut comOutPortp4ll = syncPoint12;ComOut comOutPortp4rt = syncPoint15;ComOut comOutPortp4rl = syncPoint14;ComOut comOutPortp2lt = syncPoint5;ComOut comOutPortp2ll = syncPoint4;ComOut comOutPortp2rt = syncPoint7;ComOut comOutPortp2rl = syncPoint6;ComOut comOutPortp3lt = syncPoint9;ComOut comOutPortp3ll = syncPoint8;ComOut comOutPortp3rt = syncPoint11;ComOut comOutPortp3rl = syncPoint10;

/*** Create interfaces for the coordinator:*/

CorIn corInPortp1lt = syncPoint1;CorIn corInPortp1ll = syncPoint0;CorIn corInPortp1rt = syncPoint3;CorIn corInPortp1rl = syncPoint2;CorIn corInPortp4lt = syncPoint13;CorIn corInPortp4ll = syncPoint12;CorIn corInPortp4rt = syncPoint15;CorIn corInPortp4rl = syncPoint14;

77

Page 78: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

CorIn corInPortp2lt = syncPoint5;CorIn corInPortp2ll = syncPoint4;CorIn corInPortp2rt = syncPoint7;CorIn corInPortp2rl = syncPoint6;CorIn corInPortp3lt = syncPoint9;CorIn corInPortp3ll = syncPoint8;CorIn corInPortp3rt = syncPoint11;CorIn corInPortp3rl = syncPoint10;

/*** Create components with inputs and outputs:*/

Philosopher com0_Philosopher = new Philosopher(comOutPortp1lt,comOutPortp1ll, comOutPortp1rt, comOutPortp1rl,100, -1, "Phil1");

Philosopher com1_Philosopher = new Philosopher(comOutPortp4lt,comOutPortp4ll, comOutPortp4rt, comOutPortp4rl,200, -1, "Phil2");

Philosopher com2_Philosopher = new Philosopher(comOutPortp2lt,comOutPortp2ll, comOutPortp2rt, comOutPortp2rl,300, -1, "Phil3");

Philosopher com3_Philosopher = new Philosopher(comOutPortp3lt,comOutPortp3ll, comOutPortp3rt, comOutPortp3rl,400, -1, "Phil4");

/*** Create the coordinator with inputs and outputs:*/

ChopSticks coordinator = new ChopSticks(corInPortp1ll, corInPortp1lt,corInPortp1rl, corInPortp1rt, corInPortp2ll, corInPortp2lt,corInPortp2rl, corInPortp2rt, corInPortp3ll, corInPortp3lt,corInPortp3rl, corInPortp3rt, corInPortp4ll, corInPortp4lt,corInPortp4rl, corInPortp4rt);

/*** Start the coordinator and the components:*/

com0_Philosopher.start();com1_Philosopher.start();com2_Philosopher.start();com3_Philosopher.start();

coordinator.start();

78

Page 79: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

}}

A.3.3 Generated CASP code without dead-locks

This generated code is exactly the same as the generated CASP code fromthe dining philosophers example with dead-locks. Only now the parameterfor the synchronization points of the first philosopher component is changed.The left and right release ports are interchanged, as well as the left and righttake ports.

/*** Create components with inputs and outputs:*/

Philosopher com0_Philosopher = new Philosopher(comOutPortp1rt,comOutPortp1rl, comOutPortp1lt, comOutPortp1ll,100, -1, "Phil1");

Philosopher com1_Philosopher = new Philosopher(comOutPortp4lt,comOutPortp4ll, comOutPortp4rt, comOutPortp4rl,200, -1, "Phil2");

Philosopher com2_Philosopher = new Philosopher(comOutPortp2lt,comOutPortp2ll, comOutPortp2rt, comOutPortp2rl,300, -1, "Phil3");

Philosopher com3_Philosopher = new Philosopher(comOutPortp3lt,comOutPortp3ll, comOutPortp3rt, comOutPortp3rl,400, -1, "Phil4");

A.3.4 Generated CASP code solved dead-locks with time-outs

This generated code is exactly the same as the generated CASP code fromthe dining philosophers example with dead-locks. Only now the sixth pa-rameter of the philosopher component is set to a number of milliseconds forthe time-out.

/*** Create components with inputs and outputs:*/

Philosopher com0_Philosopher = new Philosopher(comOutPortp1lt,comOutPortp1ll, comOutPortp1rt, comOutPortp1rl,100, 1000, "Phil1");

Philosopher com1_Philosopher = new Philosopher(comOutPortp4lt,comOutPortp4ll, comOutPortp4rt, comOutPortp4rl,200, 1000, "Phil2");

Philosopher com2_Philosopher = new Philosopher(comOutPortp2lt,

79

Page 80: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

comOutPortp2ll, comOutPortp2rt, comOutPortp2rl,300, 1000, "Phil3");

Philosopher com3_Philosopher = new Philosopher(comOutPortp3lt,comOutPortp3ll, comOutPortp3rt, comOutPortp3rl,400, 1000, "Phil4");

80

Page 81: Constraint Automata with Synchronization Pointsliacs.leidenuniv.nl/assets/Masterscripties/2009-07-MichielPouw.pdf · Constraint Automata with Synchronization Points M.F.A. Pouw Leiden

References

[1] Farhad Arbab. Reo: a channel-based coordination model for componentcomposition. MSCS, 14(3):329–366, 2004.

[2] Farhad Arbab. Abstract behavior types: a foundation model for com-ponents and their composition. Science of Computer Programming 55352, 2005.

[3] Farhad Arbab. Coordination for component composition. Invited Lec-ture, Proc. of International Workshop on Formal Aspects of ComponentSoftware, Macao, China, 2005.

[4] Christel Baier, Marjan Sirjani, Farhad Arbab, and Jan J. M. M. Rutten.Modeling component connectors in reo by constraint automata. Sci.Comput. Program., 61(2):75–113, 2006.

[5] SEN3 Research group. Reo homepage, April 2009.http://reo.project.cwi.nl.

[6] Ziyan Maraikar, Alexander Lazovik, and Farhad Arbab. Buildingmashups for the enterprise with sabre. Internal paper, 2008.

[7] Michiel Pouw. Reo ciruits with synchronization points. Course Report;Components, Composition and Coordination, Leiden University, 2007.

[8] Jose Proenca, Ziyan Maraikar, Dave Clarke, and Farhad Arbab. Exe-cuting reo. Internal paper, 2008.

[9] Addison Wesley. The eclipse modeling framework (emf) overview. In-ternal paper, 2005.

81