HAL Id: hal-02392909
https://hal.inria.fr/hal-02392909
Submitted on 4 Dec 2019
HAL is a multi-disciplinary open access
archive for the deposit and dissemination of
sci-entific research documents, whether they are
pub-lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d’enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.
Time analysis of actor programs
Cosimo Laneve, Michael Lienhardt, Ka Pun, Guillermo Román-Díez
To cite this version:
Cosimo Laneve, Michael Lienhardt, Ka Pun, Guillermo Román-Díez. Time analysis of actor
pro-grams. Journal of Logical and Algebraic Methods in Programming, Elsevier, 2019, 105, pp.1 - 27.
�10.1016/j.jlamp.2019.02.007�. �hal-02392909�
Contents lists available atScienceDirect
Journal
of
Logical
and
Algebraic
Methods
in
Programming
www.elsevier.com/locate/jlampTime
analysis
of
actor
programs
✩
Cosimo Laneve
a,
Michael Lienhardt
b,
Ka
I Pun
c,
d,
Guillermo Román-Díez
e,
∗
aUniversityofBologna/INRIA,ItalybONERA–TheFrenchAerospaceLab,Palaiseau,France cWesternNorwayUniversityofAppliedSciences,Norway dUniversityofOslo,Norway
eUniversidadPolitécnicadeMadrid,Spain
a
r
t
i
c
l
e
i
n
f
o
a
b
s
t
r
a
c
t
Articlehistory:
Received23March2018
Receivedinrevisedform9February2019 Accepted17February2019
Availableonline21February2019
Keywords:
Timeanalysis Behavioral types Resourceanalysis
This paper proposes a technique for estimating the computational time of programs in an actor model, which is intended to serve as acompiler target of awide variety of actor-based programming languages. We define a compositional translation function returningcostequations,whicharefedtoan automaticoff-the-shelfsolverforobtaining the timebounds.Ourapproach isbasedonanew notion ofsynchronizationsets, which captures possible difficult synchronizationpatterns between actors and helpsmake the analysis efficient and precise.The approachis proven tocorrectlyover-approximate the worst computational time of an actor model ofconcurrent programs. Ourtechnique is complementedby aprototype analyzerthat returnsupper bound ofcostsfor theactor model.
©2019ElsevierInc.Allrightsreserved.
1. Introduction
Time computation for programs running on mainstream architectures,for example, multicore, distributed systems or cloud, is intricate anddemanding as the execution of a process may be indirectly delayed by other processes running on differentmachines dueto synchronizations. The computational time of programs is particularlyrelevant in cloud ar-chitectures, where services are bound by so-called service-levelagreements (SLAs), which regulate the costs in time and assignpenaltiesfortheirinfringements [7].Inparticular,theserviceprovidersneedguaranteesthat theservicesmeetthe SLA, for example interms of the end-user response time, by deciding on a resource management policy,and by deter-mining theappropriate number ofvirtual machine instances(or containers)and their parametersettings (e.g.,their CPU speeds).
Inthispaperweproposeatechniqueforestimatingthecomputationaltimeofprogramsinanactormodel.Thismodel isintendedtoserveasacompilertargetofawidevarietyofactor-basedprogramminglanguages,suchasobject-oriented ones, including
Java
andC#
,which areusedincloud architectures.Ourtechnique aimsat(andinfact, hasbeen devel-oped for)helpingserviceproviderstoselectresourcemanagement policiesinacorrectway, beforeactuallydeployingthe service.✩ ThisworkhasbeenpartiallysupportedbyComunidaddeMadridaspartoftheprogramS2018/TCS-4339(BLOQUES-CM)co-fundedbyEIEFundsof
theEuropeanUnion,bytheSpanishMINECOprojectTIN2015-69175-C4-2-RandtheSIRIUSCentreforScalableDataAccess (http://www.sirius-labs.no).
*
Correspondingauthor.E-mailaddresses:cosimo.laneve@unibo.it(C. Laneve),michael.lienhardt@onera.fr(M. Lienhardt),Violet.Ka.I.Pun@hvl.no(K. Pun),
guillermo.roman@upm.es(G. Román-Díez).
https://doi.org/10.1016/j.jlamp.2019.02.007
Severaltechniqueshavebeenproposedforanalyzingthecomputationaltimeofsequentialprograms.Seeforexample [3,
6,10,11,17] andSection7.Ourapproachissimilarto [15],whereastaticallytypedintermediatelanguagehasbeendefined in order to verify safety propertiesand certify code optimizations. Different from [15], our language, called
alt
, short foractorlanguagewithtime,isconcurrent,andcontainsanoperation definingthenumberofprocessingcyclesrequiredto be computed, calledwait(
n)
(similarto thesleep
(
n)
operationinJava
). Inordertoanalyze thecomputationaltime ofalt
,we definean algorithmthat returnsasetofcostequationsthat areadequateforasolver. Wedemonstratethatthe solutionofthecostequationsover-approximatesthecomputationaltimeofthealt
programininput.Giventheseresults, estimatingthecomputational timeofa programinsome programminglanguagesamountstodefining acompilationinto analt
program(anddemonstratingitscorrectness).Thepresentedworkbuildsuponapreviousarticlebytheauthors [9],whereitcapturestheactormodelsofactor-based programminglanguagesintermsofbehavioral types,andobtainsthecomputationaltime ofthecorrespondingprogram by feeding the cost equations produced by a translationfunction to a off-the-shelf solver, namely the
CoFloCo
solver [8]. However, thistechniqueproposed in [9] has averysevere constraint:invocations wereadmittedonly eitheron thesame actororonnewlycreatedones,i.e.,noinvocationonparameters.Forinstance,accordingtothisconstraint,aninvocationto amethodinner
(
y,
x)
,wherethefirstparameteristheactorexecutingthemethod,cannotoccurinthebodyofamethodouter
(
x,
y)
.The challengeis that,in thiscase,computingthe cost ofouter
(
x,
y)
requiresto knowwhetherthereis a synchronizationbetweenactors x and y.Incasethereis,onehastoconsiderthatinner
(
y,
x)
mightbedelayedbyother methodsrunningon y,whichmightbeindependentfromouter
(
x,
y)
.Thispaperfocusesonovercomingthisissue.Wefirstcompute synchronizationsets ofactors, whichareactorsthat po-tentiallymightinterferewiththeexecutionsofeachother.Wethencomposethecostofaninvocationwiththecostofthe calleeintwoways:(1)itisadded,correspondingtosequentialcompositions,iftheargumentsoftheinvocationandthoseof thecallerareinthesamesynchronizationset;(2)itisthemaximumvalue,correspondingtoparallelcomposition,otherwise. Wethendefineanewtranslationfunctionthattakesthesynchronizationsetsofan
alt
programintoaccountandreturns thecorrespondingsetofcostequations.The translation of
alt
programs intothe solver input code [2,8] has beenprototyped andcan be experimented(see Section 6). This tool, together withthecompiler we havedefinedin [9], allows usto automaticallycompute the cost of programs inABS
,aprototypelanguageforprogrammingthecloud [13] thatisan extensionofalt
.Experimentalresults show that our technique is very precise when computingthe cost ofa number oftypical distributed patterns,such asfork-join ormap-reduce.
Paperoverview. The
alt
language is defined in Section 2 and we discuss in Section 3 the issues in estimating the computational time.Section4explainstheanalysisofcomputational timebymeansofatranslationfunctionthatreturns cost equations,andSection 5discusses thepropertiesofthetranslation.In Section 6,weillustrate theconversion ofthe translationoutput totheadequate formforan off-the-shelfsolver,presentourprototype,togetherwiththeexperimental resultsofourapproachandacomparisonwithothertools.InSection7,wediscusstherelatedworkanddeliverconcluding remarksinSection8.2. Thelanguage
alt
Inthissection,wedefinethesyntaxandthesemanticsof
alt
andillustratethelanguagewithsomeexamples. Syntax. We useseveral disjointsets ofnames that, for convenience, we address takingdifferentnotations oridentifiers:methodnames,rangedoverby
m
,m
,· · ·
;actor names rangedoverbyx, y,· · ·
;natural namesu, w,a, b,· · ·
;futurenamesranged overby f , g,h,
· · ·
.Thenotationsx andu denotea possiblyemptysequenceofactorandnaturalnames, respec-tively; p rangesoversequenceswhoseelementsmaybeeitheractorornaturalnames.Analt
programm
1(
p1)
=
s1,
· · · , m
n(
pn)
=
sn, main(
x,
u)
=
sisasequenceofmethoddefinitionsoftheform
m
i(
pi)
=
si.Thelastmethodisthemainmethod,wherex istheactorname executingthemainbodyandu arenaturalnames.Statements s andexpressions e aredefinedbythefollowingsyntax:s
::=
0|
ν
x;
s|
ν
f: m(
e);
s|
f;
s|
wait(
en);
se
::=
en|
xen
::=
k|
u|
en+
en(
k are natural constants)
The syntax of
alt
statements is quite basic: 0 indicates a terminated statement;ν
x is the creation of a new actor x;ν
f: m(
e);
s creates a new taskof the methodm
that is associated to the future f ; the task startsinparallel with the continuation s. The term f performs thesynchronization ofthe taskassociatedto f . Thismaycause the(busy) wait-ing forthe terminationof thetask. Thestatement wait(
en)
, where en isa naturalexpression, represents theadvance ofe time units.This isthe only terminour modelthat consumestime (a.k.a. that generates acost). Note that term en in
wait
(
en)
contains constants andnaturalnames,includingthe arithmetic binary operator+
betweenthem.These expres-sionsarealsoknownasPresburgerarithmetics,whichisadecidablefragmentofPeanoarithmeticscontainingonlyaddition.The restrictionisnecessary becausetheanalysisinSection 4cannot deal withgenericexpressions. Notethat, ingeneral, expressions e also include actor names (in the syntax of e, x also ranges over actor names), as in the method invoca-tions.
Methoddefinitionshavetheform
m
(
p)
=
νz
1;
· · · ;
νz
k;
s suchthatallactorscanonlybecreatedinthebeginningofthe method.Additionally,the methoddefinitionm
(
p)
=
s bindsnames p tothebody s.Weassume that p hasalways afixed pattern:p=
x,
y,
u,namelyp isanonemptysequencewherethefirstelementisalways anactornameindicatingthecallee ofthe method, y areactornames andu are natural names.We assume that actornames x,
y do notclash withnamesz1
,
· · · ,
zk. Therefore, methodinvocationsν
f: m(
e)
have thepattern x,
y,
e. We further assume thatalt
hasa simple type systemthat verifiesthetype correctness ofmethodapplications.Statementsνx
;
s andν
f: m(
e);
s linkthe names x and f inthecontinuationss.Forthenotionofboundnameandtheone offree name,weusethestandardoperationsof alpha-conversionandsubstitution.Itis alsoassumedthat methodnamesm
1,
· · · ,
m
n inprogramdeclarations arepairwise different.Example2.1.Toillustrate
alt
,considertheprogram:1
main
(
x,
a,
b)
=
2ν
y;
ν
z;
3ν
f: timer(
y,
a)
;
4 f;
5ν
g: timer(
z,
b)
;
6 g;
8main
(
x,
a,
b)
=
9ν
y;
νz
;
10ν
f: timer(
y,
a)
;
11ν
g: timer(
z,
b)
;
12 f;
13 g;
15timer
(
x,
n)
=
16wait
(
n);
Considermethod
main
whichisexecuted byactor x.Notethatthisactorisautomaticallycreatedwhenthemainmethod starts to run. After creating two actors y and z at line 2,main
invokestimer
(
y,
a)
and continues its execution. By bindingthisinvocationtothefuturename f andsynchronizingitimmediatelyafterwards atline4,itispossibletodelay the execution of the caller actor x until the termination oftimer
(
y,
a)
. In this case, since y has been just created,it willimmediatelyexecutetimer
(
y,
a)
andreturn(thisis nottrueingeneralbecause y mighthaveother tasksrunning). Therefore,x willwaitexactly a timeunits(effectoftheinstructionwait(
n)
atline16) beforecontinuing.Thecontinuation spawnsataskν
g: timer(
z,
b)
atline5onactorz andwaitsforitstermination,which,forthesamereasonsasbefore,will occurafterb timeunits.Overall,thecomputationaltimeofmain
isa+
b.Observethatthetimeisthesamewhenline5isreplacedby
ν
g: timer(
y,
b)
,e.g.,spawningthethreadon y insteadof z.Inthecaseof
main
,thetwoinvocationstotimer
are performedoneaftertheother,withoutanysynchronizationin between.Thusthetwotasksareexecuted inparallel,andastheyarebothsynchronizedatlines12and13,the computa-tionaltime ofmain
ismax(
a,
b)
.Observethatifline11isreplaced byν
g: timer(
y,
b)
,e.g., spawningthe threadon yinsteadofz,thecomputationaltimebecomesa
+
b.2
Twofeaturesof
alt
easeourtheoreticaldevelopment:(i)alt
actorsarestateless and(ii)methodsdonotreturnvalues. Infact,computingthecostofstatefulactorprogramsrequiresaleapofthetheory developedinthiscontributionbecause itisnecessarytotracethestateofthefields.Similarly,whenmethodsreturnavalue,itisnecessarytoestimatethevalue (isitanoldactororanewone?ifitisanaturalnumber,howlargeitis?)inordertohavesensiblecostcomputations. Semantics. The semantics ofalt
is a transition system whose states are configurations cn that are defined as fol-lows.cn ::= act(x,p,q) | fut(f,val) | invoc(x,f, m,v) | cn cn
val ::= ⊥ | p ::= s;f | f | 0
v ::= x | f | k q ::= ∅ | s;f | q q
The notation s
;
f represents the statement s where the tailing 0 isreplaced by the future name f . We use p to range over s;
f , f , and 0. A configurationcn is a nonempty set of actors, invocation messages and futures. The associa-tive and commutative union operator on configurations is denoted by whitespace. An actor is written as act(
x,
p,
q)
, where x is the identity of the actor, p is the active task, and q is a pool of either suspended or waitingtasks. Aninvocation message is denoted as invoc
(
x,
f,
m
,
v)
, where x is the callee, f the future to which the call is bound,m
the method name, and v the set of parameter values of the call. Configurations also include futures, denoted as
fut
(
f,
val)
, where f isthe futureidentity and val indicateswhether f has alreadybeencomputed, writtenas , other-wise⊥
.The transitionrules of
alt
are givenin Fig.1. Weuse an auxiliary function tobind invocations tothe corresponding methodbodies.Letm
(
x,
z)
=
s beanalt
method.Thenbind
(
y, m,
v)
=
s{
y,v/
x,z} .
(Context) cn
→
cn cn cn→
cncn (New) z=
fresh( )
act(
x,
νz
;
p,
q)
→
act(
x,
p{
z/
z},
q)
act(
z,
0,
∅)
(Get-True) act(
x,
f;
p,
q)
fut(
f,
) →
act(
x,
p,
q)
fut(
f,
)
(Get-False) act(
x,
f;
p,
q)
fut(
f,
⊥) →
act(
x,
0,
q∪ (
f;
p))
fut(
f,
⊥)
(Async-Call)[[
e]] =
v f=
fresh( )
act(
x,
ν
f: m(
z,
e);
p,
q)
→
act(
x,
p{
f/
f},
q)
invoc(
z,
f, m,
v)
fut(
f,
⊥)
(Bind-Fun) s=
bind(
x, m,
v)
act(
x,
p,
q)
invoc(
x,
f, m,
v)
→
act(
x,
p,
q∪
s;
f)
(Wait-0)[[
e]] =
0act
(
x,
wait(
e);
s,
q)
→
act(
x,
s,
q)
(Activate) act
(
x,
0,
q∪
p)
→
act(
x,
p,
q)
(Return) act(
x,
f,
q)
fut(
f,
⊥) →
act(
x,
0,
q)
fut(
f,
)
(Tick) strongstablet(
cn)
cn→ (
t cn,
t)
Fig. 1. Transition rules.
We alsousethefunction fresh
(
)
toreturneitherafreshactornameorafreshfuturename.Finally,weuseanevaluation function[
[·]
]
ofexpressionse suchthat[
[
x]
] =
x,and[
[
e]
] =
v whenevere isaconstantnaturalexpressionandv isitsvalue;[
[
e]
]
isundefinedotherwise.Thesemanticsof
alt
isalmoststandard.See,forexample [14],forasimilarsemanticsforadialectofpi-calculuswith time.Wediscussthemostrelevantrulesinthefollowing:actorcreation,methodinvocation,methodreturnandthewait(
e)
statement.
Actor creation is handled by rule New, which extends the configuration with act
(
z,
0,
∅)
where z is a fresh actor identifier.Inalt
,methodinvocationsareasynchronous:ruleAsync-Callcreatesanewinvocationpredicateinvoc(
z,
f,
m
,
v)
andanewunresolvedfuturepredicatefut
(
f,
⊥)
,whichisassociatedtotheinvocationwithafreshfutureidentifier f.The invocation predicatewill then be bound to the corresponding callee actoras one of the tasksin the task pool (cf. rule Bind-Fun). When a method terminates, rule Return sets the value ofthe corresponding future f to . Note that f is added to the end of the method body in rule Bind-Fun. In our model, wait(
e)
is the unique operation that consumes time; that is,time does not advanceas longas a wait(
e)
statement is prefixedby some active task.Forthe trivialcase wheree=
0 (seeruleWait-0),thestatementissimplydiscarded.Onthecontrary,whenaconfigurationcn reachesastable state, that is,no other transitionis possible apartfrom those evaluating the wait(
e)
statements,time advances until an actor withanon-wait(
e)
statement canproceed. Toformalize thissemantics,we first introducethe notionofstability asfollows:
Definition2.1.Lett
>
0.Aconfigurationcn ist-stable,writtenasstablet(
cn)
,ifeveryactorincn matchesoneofthefollowing forms:1. act
(
x,
wait(
e);
s;
f,
q)
with[
[
e]
] ≥
t,2. act
(
x,
0,
q)
and i. eitherq= ∅
,ii. or,foreverys
∈
q,s=
f;
p andfut(
f,
⊥) ∈
cn.Aconfigurationcn isstrongly t-stable,writtenasstrongstablet
(
cn)
,ifitist-stableandthereexistsanactoract(
x,
wait(
e);
s,
q)
with[
[
e]
] =
t.Note thatt-stable(and consequently,stronglyt-stable) configurationscannot progressanymore becauseevery actor is stuckeitheronawait
(
·)
-statementoronanunresolvedfuture.(
cn,
t)
=
⎧
⎪
⎪
⎪
⎪
⎨
⎪
⎪
⎪
⎪
⎩
act
(
x,
wait(
k);
s,
q)
(
cn,
t)
if cn=
act(
x,
wait(
e);
s,
q)
cnand k
= [[
e]] −
t act(
x,
0,
q)
(
cn,
t)
if cn=
act(
x,
0,
q)
cncn otherwise.
TogetherwiththeruleTickinFig.1,wedefinethetimeprogress ofaconfiguration.
Theinitialconfigurationofaprogramwhosemainmethodis
main
(
x,
u)
=
s andwithinvocationmain
(
z,
k)
is act(
z,
s{
k/
u
};
fstart,
∅)
where fstartisthefutureidentifierforthemainbody.Asusual,
→
∗ isthereflexiveandtransitiveclosureof→
and t⇒
is→
∗ t→→
∗.Acomputation iscn⇒ · · ·
t1⇒
tncn,thatis, cnisaconfigurationreachablefrom cn witheithertransitions
→
or⇒
t . Whenthetimelabelsoftransitionsarenotrelevantwealsowritecn⇒
∗cn.Definition2.2.Thecomputationaltimeof cn
⇒ · · ·
t1⇒
tncnist1
+ · · · +
tn.Thecomputationaltimeofaconfiguration cn,writtentime
(
cn)
,isthemaximumcomputationaltimeofcomputations start-ingatcn.Thecomputationaltime ofanalt
programisthecomputationaltimeofitsinitialconfiguration.Example2.2.Considerthefollowingmethod
main
1:1
main
1(
x,
a,
b)
=
2ν
y;
3wait
(
k0)
;
4ν
f: m
1(
y)
;
5wait
(
a)
;
6ν
g: m
2(
y)
;
7wait
(
b)
;
8 g;
9 f;
10m
1(
x)
=
11wait
(
k1)
;
12 13m
2(
x)
=
14wait
(
k2)
;
Thismethodcreatesanewactor y atline2andspawnstwotasksonitatlines4and6,respectively,wherethetwotasks willexecute inparallelwith
main
1.Theirterminationsaresynchronizedatlines8and9by meansof g and f.Notethat
main
1takesitsnaturalnumberargumentsastheinputparameterofthewait(
·)
-operationsatlines5and7,whiletheoneatline3usesa constant k0.Thus, thecomputationaltime of
main
1 dependsontheconcretevaluesof a and b.Theotherwait
(
·)
-statementsintheexampleareexecutedwithsomeconstantsk0,k1 andk2.2
Oursemanticsdoesnotexcludebehaviors ofmethodsthatperforminfiniteactionswithoutconsumingtime(preventing rule Tick to apply), such as
foo
(
x)
=
ν
f: foo(
x);
f.This kind ofbehaviors are well-known in the literature (cf. Zeno behaviors,see [14])andtheymaybeeasilyexcludedfromouranalysisbyconstrainingrecursiveinvocationstobeprefixed byawait(
e)
-statement,where e isanot-zeronatural.Asimilarparadoxicalbehavior isgee
(
x)
=
ν
y;
ν
f: gee(
y);
fthat spawnsthenewtaskonanewactor,therebycreatinganunboundednumberofactors.WefinallyremarkthatthecompositeeffectofActivateandGet-Falsemightproduceinfinitecomputationsthatdonot makeprogress,andnotimeispassing(anactorcanrepeatedlyactivateablockedtaskandthensuspenditagain).However, assuming fairnessincomputations(anenabledtaskwilleventually be executed),itispossibleto demonstratethatthese behaviors arenotpossiblein
alt
.3. Thechallengesofcostcomputationfor
alt
programsComputing the time of
alt
programs is challenging. In this section, we illustrate the difficulties by discussing four examples.Thesedifficultiesrangefromdeterminingthetasksthat cannotexecuteinparallel – thereforethecost ofeach of thesetasksmustbeadded together–,tounderstandingthetasksthatareexecutedinparallel –thus,themaximumvalue ofthecostofthetasksisselected–ortoanalyzingthewholespectrumofschedulingpoliciesbecausetheymightalsoaffect thecomputationaltime.
Example3.1. The method
main
1 in Example 2.2 invokesm
1 andm
2 on an actor that is different from the caller. Thefollowinggraphicalrepresentationsillustratefourdifferentcomputationsthatareobtainedbychoosingdifferentvaluesofa
andb.Rectanglesindarkgray representthelargestsegmentoftimethat areusedforcomputingthemaximal costofthe computations,whicharedenotedbythenamesc1,c2,c3 andc4,respectively.
Computation 1 represents an execution where a
>
k1, which leads to the execution ofm
2 on actor y starts after thetermination of
m
1. In this case, the executions of wait(
b)
andm
2 run in parallel. Thus, the cost of this computation isk0
+
a+
max(
b,
k2)
(the expression c1 inthefigure reflectsthe casewhere b≥
k2). Computation2and Computation3de-scribe computations wherea
<
k1. This leads to delayingm
2 until the executionofm
1 finishes. In Computation2, sincea
+
b<
k1+
k2,actor x hastowaitfortheterminationofm
2.Onthecontrary,in Computation3,m
2 returnsbeforeactor xfinishes theexecutionofwait
(
b)
.Finally, Computation4illustratesanexecutionwhereboth x and y havetowaiteitherfor amethodtoterminateandreturnorforexecutinganewtask.Asouranalysisaimsatfindingasoundapproximation oftimeneededforanycomputationoftheprogram,thecostof
main
1isover-approximatedbytheexpressioncmain1
=
k0+
max(
a,
k1)
+
max(
b,
k2)
For Computation 1, Computation2 and Computation4, cmain1 captures precisely the execution time. Note that the sub-expressionk0
+
max(
a,
k1)
determinesthestartingtimeofm
2onactory.However,k0+
max(
a,
k1)
isanover-approximationof thestarting time of thestatement wait
(
b)
atline7 ofmain
1, endingup ina non-precise resultfor Computation3ascmain1
>
c3.2
Anotherchallenging issuetocope withiswhenataskis delayeddueto anunresolved future(seerule Get-false). In thissituation,thecarrieractormaystartthe executionofthependingtasksandmayrescheduletheinitialtaskafterthe terminationoftheotherones.
Example3.2.Consider followingmethod
main
2,which issimilartomain
1 inExample2.2,exceptthatm
2 isinvokedonthe calleeactor x. The computationsonthe rightshow twopossible executionsof
main
2,depending onthe valuesof aand b.
In Computation1, thesynchronization g atline 8 happensbefore
m
1 terminates. In thiscase, the cost of executingm
2doesnotcontribute totheoverallcost c1.Onthecontrary,in Computation2,thecostofexecuting
m
1 doesnotcontributeto theoverall cost c2.Thereasonis thatthe valuesofa andb in thiscomputationare larger than Computation1,which
consequentlyresultsinlongertimeforexecutingwait
(
a)
,wait(
b)
andm
2 (i.e.,wait(
k2)
)onactor x thanm
1 onactor y.Theexpression
cmain2
=
k0+
max(
a+
b+
k2,
k1)
Amorecomplexscenariocanbeillustratedbyhavingtwoactors x and y spawningtasksonathirdactor z.Inthiscase, theexecutionoftaskson x and y maydelaythestartingtimeofthosespawnedon z.Asaconsequence,itmayleadtothe postponementofthesynchronizationson x andy.Determiningthedelaysofsynchronizationsiscrucial,asdiscussedinthe followingexample.
Example3.3.Considerthefollowingmethod
main
3thatcreatestwoactors y and z atline2,theninvokesm
3on y atline4and
m
1 on z at line6.The actor z isgivenasaparameterintheinvocationofm
3 (line 4)andbecomesthe carrierofm
2(line18). 1
main
3(
x,
a,
b)
=
2ν
y;
νz
;
3wait
(
k0)
;
4ν
f: m
3(
y,
z)
;
5wait
(
a)
;
6ν
g: m
1(
z);
7wait
(
b)
;
8 g;
9 f;
10m
1(
x)
=
11wait
(
k1)
;
12 13m
2(
x)
=
14wait
(
k2)
;
15 16m
3(
x,
y)
=
17wait
(
k3)
;
18νh
: m
2(
y)
;
19 h;
Thefigurebelowshowsfourdifferentcomputationsof
main
3thatcorrespondtovariousvaluesofa,b,k1,k2 andk3.In Computation1,thecostisthesumofthecostsofthewait
(
·)
statementsinmain
3.Thiscostdoesnotincludethecostofanytaskexecutedon y and z astheyarerunninginparallelwith
main
3 withoutanydelay.Computation2combinesthecostsfromactors x andz butnotfrom y becausea
>
k2+
k3.Observethatthetimeneededtostart
m
1 isdetermined bythe expressionk0+
a;observealsothat wait(
k3)
andwait(
k2)
executesequentiallyalthough theyrunondifferentactors(y and z).Notethat,wait(
b)
andwait(
k1)
areexecutedinparallelon x and z,andsincek1>
b,themaximumcostisexpressedasc2
=
k0+
a+
k1.In Computation3,we assumea
<
k3 such that theexecutionofm
1 on z startsbeforetheinvocationofm
2 on z.Thus,theexecutionof
m
2isdelayeduntilm
1hasfinished.Thecostof Computation3iscalculatedbytheexpressionc3=
k0+
a+
k1
+
k2.Computation4highlights apossible dependencyamong tasksexecuted on actors y and z.Thecost expression forthis caseisc4
=
k0+
k3+
k2+
k1,describinga sumtowhichall threeactors contribute(k0 on x, k3 on y andk2+
k1 on z).Thereasonisthata
>
k3 wherethestatement wait(
k3)
on y (line17)directlydeterminesthestartingtimeofm
2 on z,andwhichinthiscasedelaystheexecutionof
m
1 on z asaconsequence.Oneremarkabledifferencebetween Computation2and Computation4isthetimetakenbeforestarting
m
1 onactorz.InComputation2,thecostk0
+
k3 issmallerthank0+
a,causingthatm
2 isexecutedbeforem
1on z.Whentherearetwoactorswhosetaskscouldbedependent oneachother,theircostsmustbeconsideredasifthetasksareexecutedsequentially,that is,theircostsaresummedup.Thus,therelationbetweenthetasksexecutedon y andon z mustbeconsideredinorderto over-approximateall possiblecomputationsof
main
3.Consideringallpossiblevaluesof a and b,thecost expressionthatover-approximatesthecostofexecuting
main
3 is cmain3=
k0+
max(
a,
k2+
k3)
+
max(
b,
k1)
Observethatcmain3 preciselyapproximatestheoverallcostof Computation2and Computation4.However,tosafely approx-imate thelateststarting time of
m
1 incasea>
k3,the subexpressionmax(
a,
k2+
k3)
returnsk2+
k3.Thus,we havethatcmain3
>
c3,indicatingthatthisexpressionisover-approximatingthecostof Computation3.Similarly, Computation1isalso over-approximatedbyc3 asitcapturesthatthestartingtimeofm
1 isk0+
k2+
k3,whenitsstartingtimeisk0+
a.2
Thislastexamplesuggeststhat,whenamethodinvocationhasseveralactorsasarguments,thepoolsofpendingtasksof theseactorscanhaveimplicitandpossiblycomplexdependencies,i.e.,eachofthemmayinprincipleaffectthetaskpoolsof theothersbydelayingtheexecutionofthetaskstherein.Wesaythattheseactorsbelongtothesamesynchronizationset.It iscrucialtonotethatthissynchronizationrelationistransitive.Forinstance,if x and y belongtothesamesynchronization set ataprogram pointandifanewsynchronizationrelationbetween y and z isestablished bya subsequentinvocation, thenactors x, y and z belongtothesamesynchronizationsetaswell.
Thefinalexampleillustrateshowtheschedulingmightalsoaffectthecomputationaltimeofthe
alt
programs. Example3.4.The followingexampleshowsthemethodmain
4 thatspawnsthreetasksinactory inparallel–m
1,m
2 andm
3 –thatwillbeinthepoolofpendingtasksof y.Inturn,m
3 spawnsm
4inanewlycreatedactor z.We havealso highlighted two possiblecomputations of
main
4. Computation 1 illustrates an executionwhere taskm
2 isscheduledbefore
m
3.Therefore,theexecutionofm
4,spawnedbym
3,isexecutedwhenm
2 isfinished.Thisschedulingleadsto thecomputational time c1 that adds the cost of all methods. Additionally, note that differentscheduling orders in y
affecttheexecutionof
m
4 inz.Onthecontrary,in Computation2theexecutionofm
3 isscheduledbeforem
2.Inthiscase,afterexecutingwait
(
k3)
atline 16,m
4isspawnedanditsreturnissynchronizedatline 18.Notethat,asm
2 isinthepoolof pending tasksof y, it willbe executed inparallel with
m
4.The computational time of Computation 2 will be smaller:c2
=
k0+
k1+
k3+
max(
k2,
k4)
.Forthisprogram,theexpressionthatover-approximatesthecostofexecutingmain
4needstosumupthecostofallmethods: cmain4
=
k0+
k1+
k2+
k3+
k4Since ourtechniqueissound(seeSection 5fordetails),i.e., itreturnsan over-approximationforeverypossible computa-tionaltime,ittakesintoaccounteveryschedulingorderwhenmultipletaskscanbependinginthesamepool.
2
4. Theanalysisofalt
programsThis section defines the translation of an
alt
program into a costprogram, i.e., a set of cost equations m(
u)
=
exp,where m isa(cost)functionsymbolandexp isanexpressionthatmaycontain(cost)functionapplicationsoftheform: exp
::=
k|
u|
exp+
exp|
m(
e)
|
max(
exp,
exp)
In particular,cost expressionsare additions ofthefollowingtype ofelements:naturalnumbersk, naturalnames u,m
(
e)
whichreferstothecostofexecutingmethod
m
,butonlyconsideringthenaturalexpressionsine;ormax(
exp,
exp)
,which returnsthemaximumbetweentwocostexpressionsexp andexp.Givenan
alt
programP
,theanalysisiteratesindependentlyovereachmethoddefinitionm
(
x,
y,
u)
=
s inP
and trans-latesitintoacostequation oftheformm(
u)
=
exp,where m correspondsto themethodnamem
andexp encodesa cost function which correspondsto an upperbound ofthetime executingm
,withrespectto thenumerical parameters u. As hinted in our examples, the analysis performs thistranslation by studying the task pool of every actor involved inthe method’s execution, identifying an upper bound forthe ending time ofeach of its tasks,which in turngive raise to an upperboundtothecomputationaltimeofthemethoditself.In order to manage the complexity of studying task pools and the different scheduling possibilities as described in Section 3,ouranalysisusestwomajorstructures, synchronizationschema andaccumulatedcosts.Thesynchronizationschema
ofamethodgivesthesynchronizationsetofeveryactorinvolvedinthatmethod’sbody.AsdescribedinExample3.3,actors inthesamesynchronizationsetinteractoutsidethescope oftheanalyzed method,whichmeansthattheendingtime of
1
main
(
x,
a,
b)
=
2ν
y;
νz
;
ν
w;
3wait
(
k0)
;
4ν
f: m
1(
x);
5νg
: m
3(
y,
z);
6wait
(
a)
;
7νh
: m
4(
w)
;
8νi
: m
2(
z)
;
9 i;
10wait
(
b)
;
11 h;
12 f;
g;
13m
1(
z)
=
14wait
(
k1)
;
15 16m
2(
z)
=
17wait
(
k2)
;
18 19m
3(
y,
z)
=
20wait
(
k3)
;
21ν
f: m
4(
z)
;
22 f;
23 24m
4(
z)
=
25wait
(
k4)
;
Fig. 2. Running example of aaltprogram.
ataskinoneactor’staskpooldependssomehowonthetaskpoolsanditsschedulingordersofother actorsinthesame synchronizationset.Theanalysisover-approximatesthisimplicitdependencybyconsideringthepoolsofalltheseactorsas iftheywereoneuniquepool.Anaccumulatedcosts isanabstractionofataskpoolusedtogetagoodupperboundforthe endingtimeofacomputation.Themaindifficultyinidentifyingsuchanupperbound istodeterminethestartingtimeof acomputation,whichdependsonthestateofthetaskpoolitselfandonthetimeatwhichthecorrespondingmethodcall wasperformed.
4.1. Synchronizationschema
Asynchronizationset,rangedoverby A, B,
· · ·
,isasetofactornameswhosetaskshaveimplicitdependencies,thatis, the tasksofthese actorsmay reciprocally affectthetaskpools oftheother actors in thesame setby means ofmethod invocations andsynchronizations.Asynchronizationschema, rangedover byS
,S
,· · ·
, isa collectionof pairwise disjoint synchronizationsets.Thesynchronizationschemaofamethodm
isthusapartitionoftheactorsusedinthatmethodinto synchronizationsetsandisconstructedasfollows.Definition4.1(Synchronizationschemafunction).Let
S
beasynchronizationschemaands beastatement.Letsschem
(
S
,
s)
=
⎧
⎨
⎩
S
⊕ {
y,
z}
if s=
ν
f: m(
y,
z,
e)
sschem
(sschem(
S
,
s),
s)
if s=
s;
sS
otherwise whereS
⊕
A=
⎧
⎨
⎩
A ifS
= ∅
(
S
⊕
A)
∪
A ifS
=
S
∪
Aand A∩
A= ∅
S
⊕ (
A∪
A)
ifS
=
S
∪
Aand A∩
A= ∅
Let be an
alt
method definition. The synchronizationschemaS
m, wherem
(
x,
y,
u)
=
νz
1;
· · · ;
νz
k;
s, is the setS
m=
sschem
(
{{
x,
y}},
s)
.ThetermS(
x)
denotesthesynchronizationset,whichcontains x,inthesynchronizationschemaS
.The function
S ⊕
A merges aschemaS
witha synchronizationset A. Ifnoneofthe actors in A belongsto a setinS
,theoperationreducestoasimplesetunion.Forexample,letS={{
x,
y},
{
z,
w}}
.ThenS ⊕ {
x,
v}
is equalto(
{{
x,
y}}
⊕
{
x,
v})
∪ {{
z,
w}}
,whichequals{{
x,
y,
v},
{
z,
w}}
.Itisworthtoobservethatthesameresultfollowsbyswapping{
x,
y}
and{
z,
w}
(becauseelementsofS
aredisjoint).Infact{{
z,
w}} ⊕ ({
x,
y} ∪ {
x,
v}) = {{
x,
y,
v},
{
z,
w}}
.The synchronizationschema
sschem
(
S,
ν
f: m(
y,
z))
= {{
x,
y,
z,
w}}
indicatesthat all the actorsare inthe same syn-chronizationset.Onthecontrary,sschem
(S,
ν
f: m(
x,
v))
= {{
x,
y,
v},
{
z,
w}}
,becauseactors x,
v donotbelongto{
z,
w}
.We alsocompute
S
main,wheremain
(
x,
a,
b)
=
ν
y;
νz
;
νw
;
smain isthe mainmethod inFig.2.This schemaisequalto
{{
x},
{
y,
z},
{
w}}
,thatisthetaskpoolsofactors y and z may affecteach otherdueto theinvocationatline8,whereas thetaskpoolsof x and w areindependent fromtherest.Observethat,asthebody ofm
3 doesnotcontainactorcreationstatements,itssynchronizationschemaisasingletonsetthatcontainingonlyitsparameters,e.g.,
S
m3= {{
y,
z}}
.4.2. Accumulatedcosts
Inordertodefine (anover-approximation of)thetime advancementsoftasksinasamepool –e.g. inasame synchro-nizationset–weuseanextensionofthesyntaxofexp,calledaccumulatedcost andnoted
ε
,whichisdefinedasfollows:ε
::=
exp|
ε
·
m(
e),
exp|
ε
exp.
The termexp defines the starting time of a taskinvoked in an actor that doesnot belong to thesame synchronization set of the carrier. Letthis carrierbe x in the discussion below andconsider an actor y that residesin a different syn-chronization setthan thatof x. Theterm
ε
·
m(
e),
exprepresentsthe startingtime ofamethodinvokedon actor y.For example, whenx invokes a methodm
on y usingν
f: m(
y,
z,
e)
,the accumulatedcost ofthesynchronizationset of y isε
·
m(
e),
0,whereε
isthecostuptothatpoint.Timeadvancementsinthetaskofthecarrier x (e.g.,withwait(
e)
),which affectthe starting timeofsubsequent methodinvocationson y,isexpressedby addinge to exp;namely,ε
·
m(
e),
expbecomes
ε
·
m(
e),
exp+
e,which means that the starting time ofthe next method invocationon the synchronization set of y isafter thetime expressedbyε
plus the maximum betweenm(
e)
andexp+
e.The termε
exp expresses the time advancementin thecarrier x when amethod running onan actor y in adifferent synchronizationset is synchro-nized. Inthiscasethetimeadvancesby themaximumbetweenthecurrenttimeexp of x and thetimeof y,represented byε
.Following thesemanticsdescribed above, wecan definethe function
[
[
ε
]
]
that computesthetime correspondingtoε
, i.e.,the(over-approximationof)startingtimeofthenexttaskinthesynchronizationsetwhosecostisε
:[[
exp]] =
exp[[
ε
·
m(
e),
exp]] = [[
ε
]] +
max(
m(
e),
exp)
[[
ε
exp]] =
max(
[[
ε
]],
exp)
Example4.1.Thefollowingexpressions
ε
i indicatetheaccumulatedcostsinactor y forsomeinterestingprogrampointsof methodmain
1inExample2.2:3: wait
(
k0)
;
ε
3=
04:
ν
f: m
1(
y)
;
ε
4=
k0·
m1(),
05: wait
(
a)
;
ε
5=
k0·
m1(),
a6:
ν
g: m
2(
y)
;
ε
6=
k0·
m1(),
a·
m2(),
07: wait
(
b)
;
ε
7=
k0·
m1(),
a·
m2(),
bNote thateach taskcreationin y includesanewtupleintheaccumulatedcost:
m1(),
0inε
4 andm2(),
0inε
6.Notealsothattimeadvancements localinthecarrier,i.e.,actor x inExample2.2,updatethelasttupleintheaccumulatedcost withthecorrespondingexpression:a in
ε
5andb inε
7.Next, considerthe expression
ε
7=
k0·
m1(),
a·
m2(),
b. Becauseof thesynchronization g at line8ofmain
1 weobtainthefollowingcostexpression:
[[
ε
7]] =
k0+
max(
m1(),
a)
+
max(
m2,
b)
that over-approximates the worst possible time when g issynchronized. We observe that k0 is the computational time
when
m
1 isinvoked,max(
m1(),
a)
expressesthatm
1 andwait(
a)
canbeexecutedinparallel(analogouslyformax(
m2(),
b)
)andk0
+
max(
m1(),
a)
correspondstotheworstpossiblestartingtimeofm
2.Itisworthtonoticethat[
[
ε
7]
]
returnsthecost expressioncmain1 computedinExample3.1.2
4.3. Thetranslationfunction
Wehaveseenhowtheaccumulatedcostsandtheircorrespondingcostexpressionscanbecomputedforagiven synchro-nizationset.Interestingly,eachsynchronizationsethasitsownaccumulatedcost,thus,forouranalysisitisfundamentalto keeptheaccumulatedcostsseparateinordertogetpreciseresults.Inthefollowingsectionwedefinea
translate
func-tion thatcomputesthecostofamethodconsidering allpossiblesynchronizationsetsandsynchronizationsperformedon it.Thetranslationofan
alt
methodm
consistsoftwosteps:first(i)thesynchronizationschemaS
miscomputed,followingthetechniquedescribedSection 4.1,then(ii)thebodyofmethod
m
isanalyzed,byparsingeachofitsstatementsinorder. The analysis (ii)recordsthe accumulatedcosts ofsynchronization setsin translationenvironments, rangedover by,
,
· · ·
. Translation environments are maps of the formS
m(
x)
→
ε
, which relate the different synchronization sets to theircorrespondingaccumulatedcosts.Theauxiliaryoperators
and+
areusedasfollows:(
exp)(
S)
= (
S
)
exp(
+
exp)(
S
)
=
ε
·
m(
e),
exp’+
exp(
exp1+
exp)
· · · (
expn+
exp)
with
(
S)
=
ε
·
m(
e),
expexp1
· · ·
expnGivenasynchronizationschema
S
,thetranslationfunction,writtenastranslate
S(
I,
,
x,
l,
t,
s)
,takesthefollowingsix arguments:translateS(I,,x,l,t,
μ
) = ⎧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ (1) (I,+e,l,t+e) whenμ
=wait(e) (2) (I[f→S(x)], ,l+m(e),t) whenμ
=ν
f: m(y,z,e)and y∈S(x) (3) (I[f→S(y)], [S(y)→ε
· m(e),0],l,t) whenμ
=ν
f: m(y,z,e)and y∈/S(x)ε
= (S(y)) ifS(y)∈dom() t otherwise (4) (I\F,+l,0,t+l) whenμ
=fand x∈I(f) where F= {f|I(f)=S(x)} (5) (I\F, (t)\I(f),0,t) whenμ
=fand x∈/I(f) where F= {f|I(f)=S(x)or I(f)=I(f)} and t=max(t+l,[[(I(f))]]) (6) (I\F,+l,0,t+l) whenμ
=fand f∈/dom(I)where F= {f|I(f)=S(x)}
Fig. 3. The translation ofaltstatements.
i. I isamapfromfuturenamestosynchronizationsets,
ii.
isatranslationenvironment,
iii. x isthenameofthecarrier,i.e.,theactoronwhichs isexecuting,
iv. l isacostexpressionthatover-approximatesthecostofthemethodsinvokedonactorsbelongingtothesame synchro-nizationsetwherethecarrier x residesandnotyetsynchronized,
v. t isacostexpressionthatover-approximatesthecurrentcomputationalcost,whichisthecomputationaltime accumu-latedfromthebeginningofthemethodexecution,and
vi. s isasequenceofstatements,representingwait
(
e)
,ν
f: m(
e)
,or fthatmustbetranslated. andreturnsatupleconsistingofthefourelements:i. anupdatedmap I,
ii. anupdatedtranslationenvironment
,
iii. anupdatedthecostofmethodsrunningonactorsinthesamesynchronizationsetasthecarrier,and
iv. anexpressionoftheupdatedcurrentcomputationalcost. Thefunctionisdefinedonstatementsasfollows
translateS(I,,x,l,t,0)= (I,,l,t)
translateS(I,,x,l,t,
μ
;s)= translateS(I,,x,l,t,s)wheretranslateS(I,,x,l,t,
μ
)= (I,,l,t)where
translate
S(
I,
,
x,
l,
t,
μ
)
isdetailedinFig.3.Notethat,thedifficultcaseofthetranslationfunctioniswhenthe statementisatasksynchronization f,whichiscoveredbycases(4),(5)and(6).Inthefollowing,wediscussthesixcases ofFig.3indetail.Case (1): When s is a wait
(
e)
statement, thetranslate
function adds thecost e to the current cost t, which is also reflectedontheenvironmentbyupdating theaccumulatedcost ofthemethodinvocationsoneach synchronization set in
.
Cases (2)and (3): When s isamethod invocationonactor y, there aretwo subcases, depending onwhether y isinthe samesynchronizationsetofcarrier x (Case (2))ornot(Case (3)).InCase (2),thecost oftheinvocationisaddedto l and theupdated I bindsthecorrespondingfuture f to
S(
x)
.InCase (3),weaddthebindingfrom f toS(
y)
tothemap I and updatethetranslationenvironmentbyappending thecostofinvoking
m
totheaccumulatedcosttowhichS(
y)
maps. Notethat,methodinvocationsonlyincludesthenaturalexpressionsusedforinvokingm
,thatis,itincludesm(
e)
.Case (4): Thisisthefirstsub-caseoftasksynchronization whichcapturesthe situationwherethesynchronizationis per-formed on a methodwhose calleebelongs to