Modeling Behavior with UML Interactions and Statecharts
Bruce Powel Douglass, Ph.D. Chief Evangelist I-Logix, Inc. www.ilogix.com
UML is a trademark or registered trademark of Object Management Group, Inc. in the U.S. and other countries.
Page 1 About the Author
• Chief Evangelist for I-Logix •Author of • Real-Time UML 2nd Edition: Efficient Objects for Embedded Systems (Addison- Wesley, Dec. 1999) • Doing Hard Time: Developing Real- Time Systems with UML, Objects, Frameworks, and Patterns (Addison- Wesley, 1999) • Real-Time Design Patterns: Robust Scalable Architectures for Real-Time Systems (Addison-Wesley, 2002) • Advisory Board • Embedded Systems Conference • UML World Conference • Software Development Magazine •Co-chair of OMG RTAD Work Group
Page 2 Agenda
• Basic Behavioral Concepts • Interactions – Semantics of Interactions – Sequence Diagrams – Collaboration Diagrams – Using Interactions • Statecharts – Semantics of Statecharts – Statechart Notation – Activity Diagrams – Using Statecharts
Page 3 Basic Behavioral Concepts
Page 4 What IS Behavior?
• Behavior is a change in condition or value over time – May be in response to an event or request – May be externally visible or not
Page 5 What kinds of things have Behavior? • Classifiers – Big Objects •Systems • Subsystems • Components – Small Objects • “primitive” or “semantic” objects – Use Cases • Collaborations – Collaborations are groups of objects working together for a common behavioral purpose • E.g. realize a use case
Page 6 Types of Behavior • Behavior can be simple Simple behavior does not depend on the object’s history
• Behavior can be continuous Continuous behavior depends on the object’s history but in a smooth, continuous fashion
• Behavior can be stateful State-driven behavior means that the object’s behavior can be divided into disjoint sets
Page 7 Simple Behavior
• The behavior is not affected by the object’s history – cos( x ) – getTemperature( ) – setVoltage( v ) – max(a,b) b 2 – ∫ e−x dx a
• May be decomposed arbitrarily deeply into subpart behaviors
Page 8 Continuous Behavior • Object’s behavior depends on history in a continuous way. It does the same kind of behavior but resulting values vary depending on object history
X Y W V Zn – Control loops n n + n n + Ka - Delay +
Kb
– digital filter ddjj+++−−123 d j d j − fj = 4
– fuzzy logic Uses partial set membership to compute a smooth, continuous output
Page 9 State Behavior
• Behavior depends on the history of the object, but in a discrete way • Object does different kinds of behavior and accepts different events in different states – When aircraft is on the ground, landing gear cannot be withdrawn – When aircraft is ascending, landing gear cannot be lowered – When aircraft is descending, landing gear cannot be raised – When aircraft is in cruise, landing gear can neither be raised nor lowered
Page 10 Piece-wise Continuous
• A combination of state and continuous – Eg cublic splines State 1 State 2 State 3
• Performs same actions but results vary depending on object history
Page 11 Behavioral Synchronization
• BS applies to how elements synchronize with respect to the invocation of services during an interaction • Types – Synchronous • Sender blocks and waits until Receiver is done – Asynchronous • Sender “sends and continues” • Receive processes when it is ready
Page 12 Behavior the Single Thread • Single threaded behavior is EASY
Page 13 Behavior and Multiple Threads
• Independent multithread behavior is EASY
Page 14 Behavior and Chaos
• Interacting multithread behavior is VERY HARD
Page 15 Problems with Interacting Threads
• Protection of data and resource integrity in the presence contention – No problem with multiple readers – With >= 1 modifier and other accessors, the data may be corrupted or bad values may be returned • Deadlock – Happens when a resource client waits for a condition that can never happen
Page 16 Resource Contention Solutions
• Make resources reentrant – Difficult when modifying or updating a resource • Serialize access – Critical section • Disables task switching during resource access – Mutual exclusion semaphores • Implies priority inversion – Asynchronous rendezvous • Implies queuing (queue access must also be protected)
Page 17 Deadlock Prerequisites
• ALL of the following are required to have deadlock: – Mutual exclusion (locking) of resources – Resources are held (locked) while others are waited for – Preemption while holding resources is permitted – A circular wait condition exists (P1 waits on P2 which waits on P3 which waits on P1). • Liveness can be assured by breaking any of the above required conditions
Page 18 Deadlock
B
R1 Available
Locked
R2 Available 111 R1: Resource Locked 1 D 1
Task 1 Task 1 E Task 2 Active 1 1 Inactive 1 R2: C 1 Resource 1 Blocked
Task 2 Active
Inactive A Blocked
0 20 40 60 80 100 120 140 160 180 200 220 240 Time
Legend: Priority: Task 1 > Task 2 Adapted from Real-Time A: Task 2 runs with the intent of locking R1 then R2 Design Patterns by Bruce B: Task 2 locks R1 and is about to lock R2, when... C: Task 1 runs, prempting Task 2, with the intent of locking R2 then R1 Powel Douglass D: Task 2 locks R2. Addison-Wesley, 2002 E: Now Task 2 needs to lock R1, however R1 is already locked. So Task 2 must block until Task 1 can release R1. However, Task 1 cannot run to release R1 because it needs R2 which is locked by Task 2.
Page 19 (some) Deadlock Solutions
• Critical Sections – Don’t allow other tasks to run while resources are locked • Simultaneous Locking – Don’t wait while for other resources • Ordered Locking – Require locking to take place in a particular order (break circular waiting) • Priority Ceiling Protocol – Don’t allow locking of low priority resources if a higher priority resource is held
Page 20 Timing and performance
• In real-time systems, we must understand the Qualities of Service provided by the behavior – Worst case execution time – Average case execution time – Memory requirements – Write access time vs read access time • We do this by attaching constraints to the behavioral elements – Actions (on statecharts) – Methods
Page 21 Interactions
Page 22 Interaction
• A collection of communications between instances, including all ways to affect instances, – Operation invocation, – Instance creation – Instance destruction • May be synchronous, asynchronous, or a mixture • Communications are partially ordered in time
Page 23 UML Interaction Concepts
• Instance – An object •Link – A run-time connection allowing communication •Action – Specification of an executable statement •Stimulus – Communication between two instances
Page 24 UML Interaction Concepts
• Operation – Specification of a requestable service provided by an instance • Method – Implementation of an operation •Call – Specification of a synchronous communciation • Signal – Specification of an asynchronous communication • Event – An occurrence of interest that results in a signal or operation call
Page 25 Stimulus Specification
•Simple goto(x,y,z)
• With Sequence # 1.4 goto(x,y,z) – Dotted number indicates nested 1.4 newPos = goto(x,y,z) call
TaskA:1.4 newPos = goto(x,y,z) • With Thread ID TaskB:2.3 TaskA/1.4 newPos = goto(x,y,z) • With Guards and Predecessors
TaskB2.3/ TaskA: 1.4 [x^2 > y^2+z^2] newPos = goto(x,y,z)
Page 26 Interaction Notations in UML
• Sequence diagram – Most common – Emphasizes sequence over collaboration structure • Collaboration diagram – Less common – Emphasizes collaboration structure over sequence
Page 27 Sequence Diagrams • Sequence diagrams show the behavior of a group of instances over time. Instances may be – Objects (most common) – Use case instance – System – Subsystem –Actor
Page 28 Sequence Diagrams good for…
•Useful for – Capturing typical or exceptional interactions for requirements – Understanding collaborative behavior – Demonstrating that collaboration realizes use case properly – Testing collaborative behavior
Page 29 Sequence Diagrams Instance lifeline
Partition line stimulus
description
Time constraint
Collaboration boundary
Page 30 SDs for Use Case Details
• Capture interactions of System (or the use case) under consideration and actors • Used in a “black box” manner • Show typical and exceptional scenarios of use case, one scenaro per sequence diagram • Commonly a dozen to several dozen scenarios per use case
Page 31 Use case Example
Page 32 Use Case Sequence Diagram
Page 33 UC Sequence Diagram (detail)
Page 34 Use Case realization • Use cases are realized by collaborations of instances • How do you connect the use case sequence diagram to the collaboration? – How do you show it is CORRECT? • ANS: Execute Elaborated Scenarios – ADD collaboration details and show the SAME set of scenarios with this new detail – Demonstrate via execution the behavior is consistent with the required behavior
Page 35 Use Case Collaboration
Page 36 Use Case Realization
Page 37 Use Case Realization (detail)
Page 38 Special Case: Activations • Activations are useful for the sequential message exchanges
stimulus
activation
return
Page 39 Partial Ordering
• Objects are normally assumed to be potentially concurrent with other objects and so SDs only specify partial order
Page 40 Rules of (partial) Order • Message events (send or receive) on the same lifeline are fully ordered • Msg.send event precedes Msg.receive event for each message • All other orders are indeterminate
Page 41 Sequence Diagrams and States
State
• States can be shown on sequence diagrams. The states holds in time until a change of state occurs • Shows to correspondence between interaction and instance state change
Page 42 Deriving Test Vectors from Scenarios • A scenario is an example execution of a system • A test vector is an example execution of a system with a known expected result • Scenario ! Test Vector – Capture preconditions – Determine test procedure • Identify causal messages and events • Instrument test fixtures to insert causal messages – Remove optional or “incidental” messages – Define pass/fail criteria • Identify effect messages / states • Postconditions • Required QoS
Page 43 Stimulating the System
Test Environment binds actual instances to instance parameters as necessary
Test Environment or user plays the “Collaboration Boundary”
Test Environment binds actual values to passed operation parameters as necessary Page 44 Collaboration Diagrams
• “Approximately isomorphic” to sequence diagrams • Show basically same things • Emphasize object structure over sequence • Not as commonly used as sequence diagrams
Page 45 Collaboration Diagrams
• Basically, an object diagram showing – Instances –Links – Messages with sequence numbers • Caveat – Sequence is more difficult to follow – You may have to maintain numbers manually (tool dependent) • Solution – Use sequence diagrams to show scenario – Use class & object diagrams to show structure when necessary
Page 46 Collaboration Diagrams
Page 47 Statecharts
Page 48 Finite State Machines
•A finite state model is the description from which any number of instances can be made •A finite state machine (FSM) is an object which has state behavior defined by – A finite set of states – A finite set of transitions •So, – What’s a state? – What’s a transition?
Page 49 Statecharts
• What’s a state?
A state is a distinguishable, disjoint, orthogonal ontological condition of an objects that persists for a significant period of time
• What’s a transition? A transition is a response to an event of interest moving the object from one state to another
Page 50 Statecharts
• What’s an action? An action is a run-to-completion behavior. The object will not accept or process any new events until the actions associated with the current event are complete. • What’s the order of action execution? (1)exit actions of current state (2) transition actions (3) entry actions of next state
Page 51 Example States: Switch
• State: Off • State: On
Page 52 Example States: Oregon Weather
• State: Raining • State: Going to Rain
Page 53 Sample Transition: Elevator
Page 54 Actions • Actions run to completion – normally actions take an insignificant amount of time to perform – they may be interrupted by another thread execution, but that object will complete its action list before doing anything else • Actions are implemented via – an object’s operations – externally available functions – Simple statements (e.g. “x += c*sqrt(d)”) • They may occur when – A transition is taken – A state is entered – A state is exited
Page 55 Actions
• Assign to a state when they are always executed on state entry or exit
• Assign to transition when they they are not always executed on state entry or exit
Page 56 Activities
• Activities are behaviors that are executed as long as an object is in the state • Activities are not run-to-completion – They may be interrupted by an incoming event • Indicated using – “do /
Page 57 A Simple FSM
• You are implementing a reliable transmission service for an OSI-compliant protocol stack. • A message is sent that requires the receiver to return an ACK. • If an ACK does not occur, retransmit the message • If the message is transmitted 5 times without an ACK, then inform the sender.
Page 58 What’s the Object?
reactive object
Page 59 Message Transaction FSM
Page 60 Harel Statecharts
• Created by David Harel of I-Logix in late 1980s • Forms the basis for the behavioral model of the Unified Modeling Language • Supports – Nested states – Actions and Activities – Guards –History – Broadcast Events – Orthogonal Regions (AND-States)
Page 61 Basic Syntax 1
guard event parameters action list event name
A T1(int r)[r < 0] / f(r) entry / g(x), h(y) B exit / m(a), n(b) entry actions do / act(a,y,z) exit actions defer / e1, e2 e3 / p(x,y), q(z) activities state name deferred events state internal transition
Page 62 Transitions: Sending Events
• Comma separated list of transitions that occur in other concurrent state machines because of this transition
• A.k.a propagated events
tm(eventTime) / target -> genSignal(evClockTick)
Page 63 Transitions: Guards
• A guard is some condition that must be met for the transition to be taken • Guards can be – Variable range specification – Concurrent state machine is in some state [IN(X)] – Some other constraint (preconditional invariant) must be met
Page 64 Handling Transitions
• If an object is in a state S that responds to a named event E, it will act on it – Transition to the specified state if • the event triggers a named transition and • the guard on the transition (if any) evaluates to TRUE • Includes executing transition actions and propagating specified events
– Handle the event without changing state if the event triggers a named reaction • Includes executing action list associated with reaction
– Defer the event if in a defer clause
Page 65 Handling Transitions
• Events are quietly discarded if – A transition is triggered but the transition’s guard evaluates to FALSE
– A transition to a conditional pseudostate is triggered but all exiting transition guards evaluate to FALSE
– The event does not explicitly trigger a transition, reaction, or deferment
Page 66 Types of Events • UML defines 4 kinds of events – Signal Event • Asynchronous signal received • e.g. evFlameOn – Call Event • operation call received • e.g. op(a,b,c) – Change Event • change in value occurred – Time Event • Relative time elapse • Absolute time arrived • e.g. tm(PulseWidthTime) Page 67 Types of Events • Events are occurrences of interest that have both – Location – Absolute time of occurrence • Signal events associate with Signals • A Signal is a specification of an asynchronous communication between structural elements (e.g. objects) • One type of Signal is Exception
Page 68 Null-Triggered Transitions
• A.k.a. “Completion Transitions” • Triggered upon completion of – entry actions, and – any state activities • May contain a guard condition • Will only be evaluated once, even if guard condition later becomes true
Page 69 Null-Triggered Transitions
S entry/ F() do/ act() [g] T
E
Null-triggered transition trigger immediately upon completion of action F() and activity act(). If g evaluates to FALSE, then the ONLY WAY it will ever be evaluated again is if event E occurs, retriggering the null-triggered transition.
Page 70 Basic syntax 2 state
ev_2 nested state or-states
Page 71 Nested (OR) States • Improves scalability • Increases understandability • Permits problem decomposition (divide-and conquer) • Methods – Nested states on same diagram – Nested states on separate diagram • aka “submachines”
Page 72 Submachines
Has submachine
Referenced submachine
Page 73 Submachines: Reference and Stubstates
On stub state done(defaultMode) Self Testing Operating reference include / BITSubmachine include / OpsSubmachine RAM Test toOn(mode: tMode) doTest Normal Failsafe defaultMode = mode; device Test
Abort [else] Off doRAMtest [recoverOK] doDeviceTest C Unrecoverable errorFound toOff Error
errorHandled submachine indicator
Page 74 Submachines: Referenced
submachine
BITSubmachine OpsSubmachine Normal entry / isError = false; doRAMtest doDeviceTest done Testing Normal ROM (m: tMode) Mode Testing RAM [m == normal] C [else] Testing RAM Test Components Demo Mode
errorFound/ [m == failsafe] isError = true; device Test Failsafe Abort Logging Mode stub state Test [else] Results C [isError == false] Failsafe toOff errorFound doTest done Normal subEnd
Page 75 Order of Nested Actions • Execute from outermost - in on entry • Execute from innermost - out on exit
U entry: f( ) first f( ) then x(c) exit: g(a,b) U1 entry: x(c ) A exit: y()
first y( ) then g(a,b )
Page 76 AND-States • States may be decomposed into either –OR-States • A superstate may be decomposed into any number of OR-States • When the object is in the superstate, it must be in exactly one of its OR-substates. – AND-State • A superstate may be decomposed into any number of AND-States (regions of behavioral independence) • When in the containing superstate, the object must be in EVERY active AND-substate • Shown with dashed line • a.k.a “Orthogonal regions” Page 77 AND-States & Concurrency
• AND-states are not necessarily concurrent in the thread or task sense • UML uses active objects as the primary means of modeling concurrency • AND-states may be implemented as concurrent threads, but that is not the only correct implementation strategy
Page 78 Basic syntax 3 and-states
join fork
Page 79 AND-State Communication • AND-states may communicate via – Broadcast events • transitions to the object are received by all active AND-states – Propagated events • A transition in one AND-state can send an event that affects another – Guards • [IS_IN( state )] uses the substate of an AND-state in a guard – Attributes • Since the AND-states are of the same object, they “see” all the attributes of the object
Page 80 Basic syntax 4: pseudostates
initial pseudostate history pseudostate
conditional terminal pseudostate pseudostate
Page 81 Pseudostates
Symbol Symbol Name Symbol Symbol Name Branch Pseudostate (type of C or H (Shallow) History Pseudostate junction pseudostate)
T or Terminal or Final Pseudostate H* (Deep) History Pseudostate
* or n Synch Pseudostate Initial or Default Pseudostate
Fork Pseudostate
Junction Pseudostate
Join Pseudostate Merge Junction Pseudostate [g] (type of junction pseudostate) Choice Point Pseudostate Stub Pseudostate [g] label
Page 82 “Synch” Pseudostate
• Allows a special kind of guard in which a “latch” remembers that a specific transition has occurred • Similar to Petri net “place” with explicitly indicated capacity • Must synchronize across AND-States
Page 83 “Synch” Pseudostate
Data Processing
Waiting for Processing Logging Data Datum Data
dataSignal Synch Pseudostate with unbounded synch state multiplicity * User Monitoring
/active alarm ct = 0 Applying Alarm Filters Idle Waiting to Process done tm(displayTime) Alarms alarmRaised
C [active alarm ct > 0]/ genSignal(alarmRaised) Waiting to [else] accept
Displaying accept /active alarm ct = 0 Alarms
Alarm 1 Processing synch state Page 84 Inherited State Behavior
• Two approaches to inheritance for generalization of reactive classes – Reuse (i.e. inherit) statecharts of parent – Use custom statecharts for each subclass • Reuse of statecharts allows – specialization of existing behaviors – addition of new states and transitions – makes automatic code generation possible
Page 85 Inherited State Behavior
• Subclasses may be – Specialized • Statechart specialization – Substates may be added – Transitions may be rerouted – Action lists may be modified – Extension • Statechart extension – New states added – New transitions added – New action lists added
Page 86 Inherited State Behavior
• Assumes Liskov Substitution Principle for generalization: A subclass must be freely substitutable for the superclass in any operation • You CAN – Add new states – Elaborate substates in inherited states – Add new transitions and actions • You CANNOT – Delete inherited transitions or states
Page 87 Example: Generalization
Blower
Switch On / Off f( )
On Switch Off
modified action list
Base class statechart Dual Speed Blower
Switch On / new substates Off g( ) On toHigh Low Switch Off / h( ), High new transitions k( ) toLow
modified action list Dual Speed MultiHeat Blower On new and-substates Switch On toCool Off
modified action list Low Cool
toHigh Warm Switch Off / toLow Hot k( ) High
toHot toWarm
Page 88 Ill Formed Statecharts Race condition
e2 No default state
e3 Must be the same event into a join
Race condition
(attempted) use of side Non-exclusive effects of action in guard guards Page 89 Executing Statecharts
Page 90 Balancing Parentheses
• Build a machine that can balance arbitrary parenthetical expressions • Note that no FSM can do this because it requires an infinite set of states or memory: – ‘(‘ ‘((‘ ‘(((‘ ‘((((‘ are all different conditions
( ( ) ( ) . . . input stream
balanced state indicator unbalanced
FSM Page 91 Balancing 4 Parentheses )(( ))((
)(( ))( )(( ))() )( ) )) )()( )))( )() ))) )()) )))) Empty ()(( (((( ((( ()( ()() ((() (( ( () (()( ())( (() ())
(()) ()))
Page 92 Balancing Parentheses (with Memory)
• If we add a counting machine (i.e. memory), we can build a simple FSM if we note that are conditions met by all valid expressions states: – The number of characters is even (0, 2, 4, ...) – The number of left parentheses equals the number of right parentheses – The next token received when the state corresponds to a balanced expression must be a left parenthesis.
Page 93 Balancing Parentheses (with Memory)
Page 94 Balance ‘( ( ) )’
Current state
Page 95 Balance ‘( ( ) )’
Current state
Page 96 Balance ‘( ( ) )’
Current state
Page 97 Balance ‘( ( ) )’
Current state
Page 98 Example 2: ‘( ) ) ( ) ’
Current state
Page 99 Example 2: ‘( ) ) ( ) ’
Current state
Page 100 Example 2: ‘( ) ) ( ) ’
Current state
Page 101 Dueling Reactive Objects
ObjectSource
State1
s / State1 genSignal(T1(17, 3.14159), OB1, OB2)
source11 source event event reception multicasting with with parameter event parameters processing firstTarget 1 1 secondTarget OB1 OB2
T1(d: int, e:float) / StateW T1(a: int, b:float) / h += d / (e+d); StateX c = b^a;
StateY StateV event reception with parameter processing Page 102 Example: Jolt Cola Machine Class Diagram
Page 103 Example: Jolt Machine Class Diagram
submachine reference
Page 104 Substate: DispensingCan
substate connector
submachine statechart
Page 105 Class Button FSM
Page 106 Implementation of statecharts
Page 107 Simple Approach #1 • Use nested CASE statements to implement state case (state1) { switch(event) { case e1: ….; break; case e2: ….; break; } case state2 : switch(event) {…. •Problems – Performance – Scalability – Code bloat with generalization of reactive classes – Not thread safe (need to add mutex semaphore to protect all event acceptor operations), or serialize via queuing events)
Page 108 Simple Approach #2
• Use a single state variable (class attribute) which holds the current state • Event acceptor operations – actions of event acceptor operations vary depending on the value of the state variable – event acceptor operations update this state variable to change state • Problems – All clients need to know how to call all the different event acceptors – Scalability – Thread safety (same as approach 1)
Page 109 Simple Approach #2
•Example myClass::AcceptTurn(int nClicks) { if (stateVar = OPERATIONAL) { display(nClicks); clicks += nClicks; if (clicks > MAX) stateVar = OVERFLOW; }; // end if };
Page 110 Approach #3: State Pattern
State Pattern
Context Abstract Concrete State State Context 1 Abstract State {abstract}
Current State
Accept(event)
* Concrete State
Page 111 Approach #3: State Pattern
• Good when some set of states are long lasting • Good to optimize rapidly-changing states by making less-frequent state changes more expensive • Memory impact – Less memory required when statecharts are inherited – May require additional memory if there is not much specialization
Page 112 Approach #3: State Pattern «context» «context» «context» Pacing Idle Mode AAI Mode Engine Turn On create( ) To AAI destroy( ) create( )
Refractory
tm(Ref Time)
Waiting A Sense accept( A Sense)
Waiting
tm(A Sense Time)
Pacing
Page 113 Approach #4: State Table Pattern
These dependencies allow transitions and states to call State Table operations within Context as Pattern actions. Context Transition State State The state table is oriented as a Table state x transition matrix allowing access in a single probe «callback» Transition Context nextState 1 guard state space, accept transition space setDefault 1 «callback» addGuard* StateTable State Table State Template 1 * currentState stateID entry1 entry exit exit activity activity
Page 114 State Table Pattern
• Good for large state spaces • Good for constant run-time performance • More complex and expensive to set up
Detailed C++ code for this pattern can be seen in Real-Time UML 2nd Edition: Developing Efficient Objects for Embedded Systems, Addison-Wesley, 1999
Page 115 State Table Pattern
«context» «state table» «state» «state» «transition» theContext StateTable State 1 State 2 Trans 1
create
Page 116 Some References of Interest
Page 117