• Aucun résultat trouvé

Tight Integration of Java and Petri Nets

N/A
N/A
Protected

Academic year: 2022

Partager "Tight Integration of Java and Petri Nets"

Copied!
6
0
0

Texte intégral

(1)

OlafKummer

UniversitätHamburg,FachbereichInformatik

Vogt-Kölln-Straÿe30, D-22527Hamburg

[email protected]

Abstract

In this paper we investigate how the Java programming language can be integrated in an

object-orientedPetrinetformalism. Itbecomesapparenthowacarefullydesigned unication

algorithmsupportsthisgoal,despitethefactthatJavaitselfisnotbasedonunication. Some

dedicatedalgorithmsfor aPetrinetsimulatorareproposed.

1 Introduction

The basic net formalismdiscussed in this paper are reference nets. In reference nets, a net can

beinstantiatedarbitrarilyoftenandreferencestonetinstancescanbeused astokensinothernet

instances. Fordetailssee[6]. ReferencenetsuseavariantofJavaastheirinscriptionlanguage. See

[2]fortheoriginalJavaspecication.

Thispapercanbeseenasacompaniontotheearlierwork[4],wherethereferencenetformalism

andthelargescalearchitectureofthePetrinetsimulatorRenewaredescribed. Herewewilldiscuss

somefurtheraspectsthatwereonlyverybrieysketchedin[4].

2 Tuples

The Java languagehas no support for tuples. Theonly case where tuples would come inhandy

inJavawouldbemulti-valuereturns. However,theseoccurnotveryoftenandcanbesubstituted

bythereturnofacomplexobjectthataggregatesthereturnvalues. Inothercases,whenwehave

multiplevaluesthat shouldbeprocessed together, wecansimply usemultiplevariablesthathold

onevalueeach.

ButforPetrinets,tuplesaremoreimportant.Itisdangeroustostorerelatedvaluesinmultiple

places,because,ifmultipletokenshavetobeputthere,tokensfordierentdatasetscanbemixed.

Tuplessolvethisproblem.

Java's syntax oers two opportunities for adding tuples. Either a tuple is written (1,2,3)

or [1,2,3]. The rst form hasthe disadvantagethat it is impossibleto write 1-tuples, because

theycouldbemistakenforgroupingoperations,e.g."string"+(true|false)wouldbeambiguous.

Hence it wasdecidedto usethesquarebracketnotation. However,whenwe wantto support lists

aswellastuples, wehaveto llboth syntactic niches. Inthat case, 1-tuplesmightbeconsidered

dispensable,but lists of length 1would bemandatory, so that the decisionwould havebeen the

otherwayround.

[father,son]

father+

" is the father of "+

["Isaac","Jacob"] son ["Jacob","Joseph"]

["Abraham","Isaac"]

Figure1: Thenettuples

Aswehavetuplesinthelanguages,itseemssensibleto provide apattern matching capability

and thusunication. In Fig.1youcan see asimpleexamplenet. Eachtoken intheplacecanbe

uniedwiththeinputarcinscriptiontoassignvaluestothevariablesfatherandson.

Itwasdecidedtoimplementanoccurrencecheckintheunicationalgorithm,i.e.,atuplemust

notcontainitself. Duetoeciencyconsiderations,thischeckisoftenomitted. Butthismightlead

(2)

canholdavalue,althoughtheyarenotsupposedtobeusedasvaluesthemselves.Unknownobjects

are theinitialvalueofvariables. Theyrepresenttheidentityofvalueswhenthevaluesthemselves

arenotyetknown. Considerforexampletwounassignedvariablesxandy. Afterunication,both

willreferencethesameunknownobjectastheirvalue. Afterunifyingxwith1,alsoywillbevalued

with1.

TheunicationalgorithmmustalsounifyordinaryJavavalues,whichcanappearascomponents

intuplesorasvaluesofvariables. Hereuniablilitycouldbebasedonidentityoronequality. Java

providesamethodequals(...) initsobjectmodelthatissupposedtotestobjectsforequalityand

an operator== thatchecksidentity. Identityis safeinthesense that itis aconstant equivalence.

Ontheotherhand,equalityissupposed tobeanequivalence,butthiscannotbeenforced,andthe

equalitycanchangeovertime.

Nevertheless, we chose equalityas the basis of unication. Firstly, it is not even guaranteed

that eventwoequaltextstringsareidentical,sothatunexpectedresultscouldoccur. Secondly,all

existingcontainerlibrariesarebasedonequality. As wehadto uselotsof containerclassesinthe

design, we had to rely on the functionality of equals(...) in any case. It turned outthat the

resultingproblemsarecomparablyminor,but stillcarehastobetaken.

The unication algorithm works in-place, i.e., the original tuples are modied, if necessary.

Similarly,thecontentsofvariablesmaybechangedbyaunication. Thiswaywecanavoidexcessive

copying during each unication. Of course, we have to add a backtracking mechanism to undo

unications,becausethestatebeforetheunicationisdestroyed. Backtrackingisinvokedwhenever

aproposed bindingofvariablesis discardedbythesimulationalgorithm.

Allmodicationsto uniableobjectliketuples and variablesare collectedinaso-called state

recorder. It is possible to have multiple state recorders that can concurrently record and undo

changesindierentuniableobjects. However,theunicationsinasingleuniableobjectshaveto

beundoneinthecorrectorder.

Pattern matching is useful for input arcs inscribed with tuples. Here one component of the

tuplemightalreadybeknowntothePetrinetsimulator,andtheremightbeveryfewtuplesinthe

place thatmatchthisvaluecomparedtothenumberofalltokens. Thereforeindexesallowaquick

lookupofpartiallyspeciedtuples. However,dueto performanceconsiderationsonlysingletuple

componentsareusedasindexes.

Ifallcombinationsoftuple componentsweremaintainedasindexes,acombinatorialexplosion

would result. Of course this means that arc inscriptionslike ["Joe","Average",phone]do not

allowan extremely ecient lookup of JoeAverage's phone numberin theplace that contains all

phone numbers,becausetwocomponentswouldhavetoberespected. However,thesimulatorwill

stilllimitits search toall Joesor allAverages, whicheverconstitutesthe smallerset. Tohelpthe

simulator,you could use nested tuples for storing the data. Now, [["Joe","Average"],phone]

doesgiveyouaconstanttimelookup,becausetherst componentofthe tuple,apairactually,is

completelyknownandformsavalidindex.

A similarindexingalgorithmmightbecontainedinseveralother simulators, but literatureon

this topicisverysparse. Only[3]givesinformationonarelatedapproach,whichissomewhatless

exible andnotasecientastheproposedscheme, however.

3 Actions

Many high-level Petri net formalisms support the execution of some additional code during the

ringofatransitionthatdoesnotinuencetheenablednessofatransition. Referencenetssupport

this concept by so-calledaction inscriptions,which cantriggerside eects, but mayalso beused

to determinethevalueofoutput arcvariables. Acommonusewouldbethetransitioninscription

action x=y.aLongMethodCall(u,v)to initiate along method call that has no inuence on the

activationofthetransition.

Becausetheresultofanactionisunknowable,wemustmakesurethateveryresultwillleadto

alegalringofthetransition. Thesimulatorshoulddetectthefollowingillegalsituations:

Avariableiscalculatedbyanactionbutisalreadycomputedduringthesearchforabinding.

(3)

becomputedbyadierentaction.

Luckily, we can integrate the detection algorithminto the already implemented unication algo-

rithm. We representan action callby a calculatorobject that is uniableonly with itself. This

objectreferencesitsarguments,whichmightbeJavaobjects,tuples,unknown,orevenothercalcu-

latorobjects. Theoccurrencecheckcanthus detecteventhose cyclesthatarise outofrecursively

embeddedtuplesandcalculatorobjects.

x

y

u

v

Figure2: Adatastructureofuniableobjects

Fig.2 visualizesthe actualdata structure generated by action x=y.aLongMethodCall(u,v).

Thevariablesaredenotedbyrectangles,thecalculatorobjectbyacircle,theunknownsbyrhombi.

Therearetwotupleobjectsdepictedastrianglesthatresultfromtheinternalrepresentationofthe

expressions. One tuple groups the argumentsand onetuple combines the target objectand the

othertuple. This simpliessomeinternalprocedures.

Atthispoint,itwouldbeimpossibleto unifyxandy,becauseacyclewouldarise. Itwouldbe

impossibletounify xwith1,becausethecalculatorobjectcanonlybeuniedwithitself.

Another part of the unication algorithmdetects when a calculatedvalue is required for the

evaluation of an input arc. In that case the transition cannot be enabled, because the value is

requiredearlytoseeifanappropriatetokenisavailable,butontheotherhand,thevaluemustnot

becomputedearly,becauseitresultsfromanaction.

Butwhathappensduringtheringofthetransition? Avaluemustbeassignedto x,therefore

thevariablemustnolongerbeboundtoacalculatorobject. Theremovalofthecalculatorobjects

is doneimmediatelyafter asuccessfulsearch. Imaginethat thesearchalgorithmhasfoundavalid

binding. An output arcexpressionhas been computed, resultinginatuple. Wecannot put that

tupledirectlyintotheplace,becausethetuple'scontentmightbesubjecttobacktracking. Therefore

wemakeacopyofall variablesandtuples andensurethat thecopiesareimmutable. Duringthis

process,whichhastobedoneinanycase,wecansafelyremoveallcalculatorobjectswithoutfurther

ineciencies. Theyserved theirpurpose of ensuringuniquelycalculated valuesand areno longer

needed.

4 Calling Nets from Java

In [5] an architecture was discussed that allows the integration of Java and Petri nets that are

implementedwiththe Design/CPNtool. UsingJava-inscribedPetrinetswecanprovidean even

smothertransitionbetweenthetwoworlds. Infact wehavealreadyseenthatcallstoJavaposeno

problemseveninthepresenceof sideeects whenweuseactioninscriptions.

Whenwewanttocallnets,wemustdenemethodsfornets. Thewishtoimplementnetmethods

isnotnewandplentyofschemeshavealreadybeendevised,[7]couldbenamedasanexample.

Inreferencenets,theonlymeansofcommunicationwithnetsaresynchronouschannels. Chan-

nelsareparameterizedandallowabidirectionalinformationtransfer. Inorderto synchronize,two

transitioninstanceshavetoagreeonachannelandonasequenceofmatchingarguments.Thetran-

sitioninstancethatinitiatesthesynchronizationmustexplicitlyreferencethenetinstancewherethe

targettransitionislocated. E.g.,net:channel(2,3,5)wouldbeaninvocationthroughthechannel

channelofatransitioninthenetnetwiththreeparameters. Thetargettransitionwouldhaveto

provideaninscriptionlike:channel(x,y,z)tosignalthat itwantstoengage insynchronizations

(4)

0 old :deposit(amount)

old+amount :amount(amount)

amount

:withdraw(amount) this:deposit(-amount)

money

amount deposit

withdraw

Figure3: Thenetaccount

Thenet fromFig. 3models avery simplebank account. The customer canonly deposit and

withdrawmoneyandviewthecurrentamount. Whatweneednowisawrapperclassthatconverts

method callsto channel invocations, so that wecan usethe net asan ordinaryJava object. We

havedescribehowtheconversionisdone.

package samples.call;

class Account for net account {

void deposit(int amount) {

this:deposit(amount);

}

void withdraw(int amount) {

this:deposit(amount);

}

int currentAmount() {

this:amount(return);

}

}

Thedeclaringpackagesamples.callisgiveninaspecialstatement. Acompilercannowbeinvoked

that convertsthedescriptionintoJavacode. Theresultingclass Accountwillbeknownasastub

class.

Eachtime yougenerateastubobject,theassociatednetisautomaticallycreated,too. Thisis

thereasonforlistingthenetnameafterthekeywordsfor netintheheader.

Thebody ofa classdescription consistsof asequence of method descriptionsand constructor

inscriptions. Inour examplewe donothaveconstructors, such that adefault constructorwillbe

automaticallyinserted. Thebodyofeachmethodconsistsofasequenceofchannelinvocationsand

variabledeclarations,separatedbysemicolons.

As in reference nets, variablesneed not be declared. If variablesare declared, they must be

declaredbeforetheyareused. Inourexampletherearenovariablesexceptfortheinputparameters

andthespecialvariablereturn,whichisusedinthelastmethodcurrentAmount(). Thisvariable

is automatically declared in each method that has a non-void return type. A non-void method

returnsthevalueof returnattheendofitsbody.

[]

acc acc

acc action acc=new

samples.call.Account() action

acc.deposit(500)

action amount=

acc.currentAmount()

account

init created deposited amount amount

create deposit query

Figure4: Thenetcustomer

(5)

vides a synchronizationrequest to the search algorithm. The search algorithm can then try to

nd anappropriatesynchronizationorreadditionalspontaneous transitionsinthecasethat the

synchronizationisnotpossibleatthemoment. Afterthesynchronizationsucceeds,thestubobject

isinformed,sothatthemethodcan return.

Itis importantto note that amethod callcanconsist of multiplesynchronizationrequests,so

that you arenotlimited to actionsthat can be performed atomicallyby asingletransition. Itis

allowedto startlarge subprocessesduringthe execution of anet method. Typically, exactlytwo

synchronizationsarerequired,oneto startthemethod,andonetocollectheresults,but thismay

vary. Acommonmethod descriptionmightbe

type method(type0 arg0, type1 arg1, type2 arg2) {

this:method(instance,arg0,arg1,arg2);

this:result(instance,return);

}

Here weprovidean additionalargumentinstancethat is set by theinvoked netduringthe rst

synchronization. It can be used during the second synchronization to collect the correct return

valuejustincasemultiplemethodcallshavebeenmade. Wedonotspecifythetypeof instance,

but itmightbeauniquecallnumberorareferencetoanetinstancethatiscreatedtoprocessthe

request.

5 Types

Although intheapplicationdomainofrapid prototypingitis desirableto haveatypefreesystem

where variablesdonothaveto be declared,it isalso usefulto havethesecurityof typechecking,

if desired. Therefore reference nets provide both a typed and an untyped formalism. Not only

variables,but also placesmaybetyped. Inbothcasesatypeguaranteesthat only valuesofthat

typemaybestoredinthetypedobject.

Number n;

Integer i;

n

n Integer

Integer

Number i

i Number

Figure5: Thenettypes

ThenetfromFig.5illustratesakeyproblemwhileimplementingatypesystem. Whichconver-

sions shouldbeallowedforinput andoutput arcs? If thearc type andthe placetypeare neither

supertypesnorsubtypesofeachother,isseemsplausibletoreportanerror. Ifthedeveloperknows

that alltransportedvaluesbelongtobothtypes,thisshouldhavebeenindicatedwithacast.

Ifthetypeoftheoutputarcinscriptionisasubtypeoftheplacetype,everythingiscorrect. But

if itisnot, wecannot besurethat the token thatis put intheplacesatises thetypeconstraint.

Thereforewehavetoreportanerrorforthelowerlefttransitioninthegure,becauseanumberis

notnecessarilyaninteger.

Perhapssurprisingly,weallowbothsupertypeandsubtyperelationsforinputarcs. Iftheresult

of aninputarcexpressionturns outtobeofthewrongtype, itisguaranteedthat noappropriate

tokenisintheplace,sothatthis bindingisnotenabledanyways. Ontheotherhand,iftheinput

arcisinscribedwithasubtypeoftheplacetype,wesimplyhavetomakesurethatonlythosevalues

thatarepermissibleareuniedwiththevariable. Othertokensintheplacearesimplyignored.

TheJavatypesystemisrelativelystraightforward,butithasafewroughedgesthatstemfrom

Java's origininC++. Especially, Javawillgladlyconvert 32-bitintegersto 32-bitoating point

numbersorviceversa,althoughinformationislostintheprocess.

This is acceptable, albeit dangerous, for ordinaryassignmentsor method calls. Fortoken re-

(6)

withanintegervariable. Itisnotclearwhetherweshouldacceptthelossthatresultsfromconvert-

ingoattokenstointegervalueswhenassigningthevariableorthelossthatresultsfromconverting

theintegervaluetoaoat,sothat thetokencanberemoved.

Therefore a new subtype relation losslessly convertible was introduced into the system. It is

only usedfortypecheckingarcsandit diersfromthenormalsubtyping relationbynotallowing

conversionsfromlongstoeitheroatsor doublesandfromintegerstooats. Formethod callsthe

ordinaryJavasemanticswasretained toachievecompatibility.

Synchronouschannelsareuntyped. Becausethedirectionofinformationtransferisunspecied

forchannels,theconceptoflosslessconvertibilitywillbeusedhere,too,ifitisdecidedtoaddtyped

channelsinthefuture.

Atthemoment,tupleshaveonecommontype,aswedonotdierentiatebetweenintegertriples,

stringpairs,tuplesofarbitraryobjects,andsoon. Typedtupleswouldbeavaluableaddition,but

at themomenttherearetoomanyconictingapproaches,noneof which issupportedbytheJava

environment. Theseissuesshouldprobablybepostponeduntil ithasbeennallydecidedwhether

andhowtointegrateparameterizedtypesintheJavalanguage.

6 Conclusion

We haveseenhowaproperintegrationofJavaandPetrinetsleadstovariousdesigndecisionson

boththe net formalismand itsimplementation. Starting with tuples werequired unication and

patternmatching. Wesawthatactioninscriptions,whichgreatlyaddtoexpressiveness,gaveriseto

asurprisingextensionof theunicationalgorithm. Thewish foraseamlessintegrationmotivated

callsfromJavatonets,whicharesupportedbyautomaticallygeneratedstubobjects.Allalgorithms

havebeenimplementedinRenew1.1, whichisfreelyavailable[6].

References

[1] SørenChristensenandNielsDamgaardHansen. ColouredPetrinetsextendedwithchannelsfor

synchronouscommunication. TechnicalReportDAIMIPB390,AarhusUniversity,1992.

[2] JamesGosling,Bill Joy, and Guy Steele. The Java Language Specication. The JavaSeries.

Addison-Wesley,1997.

[3] TorbenBisgaardHaaghandTommyRudmoseHansen. OptimisingacolouredPetrinetsimula-

tor. Master'sthesis,UniversityofAarhus,December1994.

Availableathttp://www.daimi.au.dk/CPnets/publ/thesis/HanHaa1994.pdf.

[4] Olaf Kummer. Simulating synchronous channels and net instances. In J. Desel, P. Kemper,

E.Kindler,andA. Oberweis,editors,5.WorkshopAlgorithmen und WerkzeugefürPetrinetze,

ForschungsberichtNr.694,pages7378.FachbereichInformatik,UniversitätDortmund,October

1998.

[5] OlafKummer,DanielMoldt,andFrankWienberg.Symmetriccommunicationbetweencoloured

Petri netsimulationsand Java-processes. In SusannaDonatelli and Jetty Kleijn,editors,Ap-

plication and Theory of Petri Nets 1999, volume1639 of LectureNotes in Computer Science,

pages86105.Springer-Verlag,1999.

[6] Renew the reference net workshop. WWW page at http://www.renew.de/. Contains the

documentationforRenewandanintroductionto referencenets.

[7] C.Sibertin-Blanc.Cooperativenets.InR.Valette,editor,ApplicationandTheoryofPetriNets

1994,Proceedings15th InternationalConference, Zaragoza, Spain,volume815ofLectureNotes

inComputer Science,pages471490.Springer-Verlag,1994.

Références

Documents relatifs

The concurrent step reachability graph of a Petri net has all reachable markings m as vertices, a distinguished initial marking m 0 and an arc labelled by U leading from m to m 0 when

– by removing parallel composition from Petri nets with control flow and adding an exception control flow as white tokens in addition to black tokens, we have defined Petri nets

Doing so, zinc allows to substantially extend snakes and Neco in various ways: efficient firing and statespace computation, Petri nets coloured by potentially any programming

In timed nets [65], [70], [83], firing times are associated with transitions, and transition firings are real–time events, i.e., tokens are removed from input places at the beginning

In an ongoing example reconfigurable Petri nets are used to model and to verify partial dynamic reconfiguration of field programmable gate arrays using the tool ReconNet ([5] or

The presented approach combines two popular Petri nets modelling environments (TINA [3] and CPN Tools [9]) with a mainstream model checker for temporal logic (NuSMV [5], [4])..

Its functionality is straight forward: if an exception is thrown during the execution of a transition inscription (in our case Java code) while firing, the exception object is put

While minimality could be easily related to set inclusion of the transition sets of two standard Petri nets, the diculty for extended Petri nets with priorities is that