putting events in context - purdue university · putting events in context aspects for event-based...

13
Putting Events in Context * Aspects for Event-based Distributed Programming A. Holzer 1 L. Ziarek 2 K.R. Jayaram 3 P. Eugster 3 1 LARIM, Polytechnique de Montréal, QC H3C-3A7, Canada 2 Fiji Systems LLC, Indianapolis IN 46202, USA 3 Department of Computer Science, Purdue University, IN 47906, USA ABSTRACT Event-based programming is an appealing paradigm for de- veloping pervasive systems since events enable the decou- pling of interacting components. Unfortunately, many event- based languages and systems have hardwired notions of phys- ical or logical time and space. This limits their adaptability and target deployment environments, as pervasive systems rely on inherent interaction and interchanging of different protocols and infrastructures. This paper thus introduces domain-specific aspects for cap- turing event context, generalizing beyond the classic time and space dimensions associated with events. Through ex- amples, we demonstrate that our context aspects — con- spects for short — modularize the design and implemen- tation of event contexts, enabling code reuse, and making programs portable across infrastructures. We illustrate the benefits of conspects by using them to transparently switch protocols in two pervasive software suites implemented in EventJava: (1) a tornado monitoring system deployed on different architectures ranging from desktop x86 to embed- ded LEON3, and (2) a mobile social networking suite with protocols for different application scenarios. 1. INTRODUCTION Distributed applications are inherently hard to program, requiring developers to walk a thin line between dealing with specifics of the targeted distributed environment and creat- ing generic and reusable components. These concerns are exacerbated in pervasive systems which need to deal with mobility or wireless communication. Software specialization concerns in distributed systems, however, can be mitigated through the use of adequate ab- stractions. For example, architectural patterns such as pub- lish/subscribe or programming languages [13, 16] centered around explicit events yield a higher-level model of the un- * This research is partially funded by the Swiss National Sci- ence Foundation through project number PBLAP2-127668 and by the US NSF through grants 0644013 and 0834529. Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. Copyright 20XX ACM X-XXXXX-XX-X/XX/XX ...$10.00. derlying message-passing infrastructure, abstracting data rep- resentation and communication properties. By communicat- ing indirectly via production/consumption of event notifi- cations, event-based components can remain largely decou- pled, separating communication from computation. More recently, there has been increased interest in raising the level of abstraction by reasoning in terms of complex events com- posed from simpler ones. Several programming languages have thus been extended for event correlation [3, 8, 12, 17, 21, 30, 34, 38]. A closely related paradigm is stream pro- cessing, which allows components to operate over specific sequences of events [36, 37]. Unfortunately, current languages which support complex events do not provide adequate abstraction from underly- ing distributed communication protocols, thereby being tied to specific environments or infrastructures by caveat. As an example, consider events being correlated in a pervasive system. To perform simple time- or order -based correla- tion ` a-la e1 <e2 on two events e1 and e2 where the former must proceed the latter, clearly some form of timestamps are required. Even in the absence of explicit operators for order-based correlation, several distributed correlation lan- guages have recently turned to models based on order of event occurrence or reception [30, 38], which requires some form of timestamps. With event stream models, such or- der is often implicit: correlating over a sequence of m events e [0]...e [m-1] implies that e [i] precedes e [i+1] i [0..m-2]. Yet, depending on the underlying environment, clocks may be only weakly synchronized, or not at all, making logi- cal clocks such as Lamport clocks [24] or vector clocks [25] necessary. This in turn affects the underlying communica- tion protocols as these rely on such information to ensure temporal constraints or order. The choice of protocol is, thus, dictated by the exact deployment environment. Simi- larly, many distributed applications involving mobile clients are nowadays developed with an inherent notion of local- ity based on positioning mechanisms (e.g., GPS, Galileo, RFID). Location-based publish/subscribe [11, 15, 26] is a corresponding event-based programming model, where event publications and subscriptions can be parametrized by abso- lute (coordinates) and relative (range) spatial criteria. The exact representation and handling of positioning information will however strongly depend on the technology at hand. It is thus desirable to abstract time, space, and other prop- erties commonly associated with events such as event au- thenticity, history, or confidence levels by a notion of event context to further separate the design and implementation of corresponding issues from the base logic of the software com-

Upload: others

Post on 10-Oct-2019

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

Putting Events in Context∗

Aspects for Event-based Distributed Programming

A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3

1LARIM, Polytechnique de Montréal, QC H3C-3A7, Canada2Fiji Systems LLC, Indianapolis IN 46202, USA

3Department of Computer Science, Purdue University, IN 47906, USA

ABSTRACTEvent-based programming is an appealing paradigm for de-veloping pervasive systems since events enable the decou-pling of interacting components. Unfortunately, many event-based languages and systems have hardwired notions of phys-ical or logical time and space. This limits their adaptabilityand target deployment environments, as pervasive systemsrely on inherent interaction and interchanging of differentprotocols and infrastructures.

This paper thus introduces domain-specific aspects for cap-turing event context, generalizing beyond the classic timeand space dimensions associated with events. Through ex-amples, we demonstrate that our context aspects — con-spects for short — modularize the design and implemen-tation of event contexts, enabling code reuse, and makingprograms portable across infrastructures. We illustrate thebenefits of conspects by using them to transparently switchprotocols in two pervasive software suites implemented inEventJava: (1) a tornado monitoring system deployed ondifferent architectures ranging from desktop x86 to embed-ded LEON3, and (2) a mobile social networking suite withprotocols for different application scenarios.

1. INTRODUCTIONDistributed applications are inherently hard to program,

requiring developers to walk a thin line between dealing withspecifics of the targeted distributed environment and creat-ing generic and reusable components. These concerns areexacerbated in pervasive systems which need to deal withmobility or wireless communication.

Software specialization concerns in distributed systems,however, can be mitigated through the use of adequate ab-stractions. For example, architectural patterns such as pub-lish/subscribe or programming languages [13, 16] centeredaround explicit events yield a higher-level model of the un-

∗This research is partially funded by the Swiss National Sci-ence Foundation through project number PBLAP2-127668and by the US NSF through grants 0644013 and 0834529.

Permission to make digital or hard copies of all or part of this work forpersonal or classroom use is granted without fee provided that copies arenot made or distributed for profit or commercial advantage and that copiesbear this notice and the full citation on the first page. To copy otherwise, torepublish, to post on servers or to redistribute to lists, requires prior specificpermission and/or a fee.Copyright 20XX ACM X-XXXXX-XX-X/XX/XX ...$10.00.

derlying message-passing infrastructure, abstracting data rep-resentation and communication properties. By communicat-ing indirectly via production/consumption of event notifi-cations, event-based components can remain largely decou-pled, separating communication from computation. Morerecently, there has been increased interest in raising the levelof abstraction by reasoning in terms of complex events com-posed from simpler ones. Several programming languageshave thus been extended for event correlation [3, 8, 12, 17,21, 30, 34, 38]. A closely related paradigm is stream pro-cessing, which allows components to operate over specificsequences of events [36, 37].

Unfortunately, current languages which support complexevents do not provide adequate abstraction from underly-ing distributed communication protocols, thereby being tiedto specific environments or infrastructures by caveat. Asan example, consider events being correlated in a pervasivesystem. To perform simple time- or order -based correla-tion a-la e1 < e2 on two events e1 and e2 where the formermust proceed the latter, clearly some form of timestampsare required. Even in the absence of explicit operators fororder-based correlation, several distributed correlation lan-guages have recently turned to models based on order ofevent occurrence or reception [30, 38], which requires someform of timestamps. With event stream models, such or-der is often implicit: correlating over a sequence of m eventse[0]...e[m−1] implies that e[i] precedes e[i+1] ∀i ∈ [0..m−2].

Yet, depending on the underlying environment, clocks maybe only weakly synchronized, or not at all, making logi-cal clocks such as Lamport clocks [24] or vector clocks [25]necessary. This in turn affects the underlying communica-tion protocols as these rely on such information to ensuretemporal constraints or order. The choice of protocol is,thus, dictated by the exact deployment environment. Simi-larly, many distributed applications involving mobile clientsare nowadays developed with an inherent notion of local-ity based on positioning mechanisms (e.g., GPS, Galileo,RFID). Location-based publish/subscribe [11, 15, 26] is acorresponding event-based programming model, where eventpublications and subscriptions can be parametrized by abso-lute (coordinates) and relative (range) spatial criteria. Theexact representation and handling of positioning informationwill however strongly depend on the technology at hand.

It is thus desirable to abstract time, space, and other prop-erties commonly associated with events such as event au-thenticity, history, or confidence levels by a notion of eventcontext to further separate the design and implementation ofcorresponding issues from the base logic of the software com-

Page 2: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

ponents. Event contexts are instantiated upon event pro-duction and considered throughout event propagation, cor-relation, and handling. Any of these stages may involve theexecution of context-specific code, making contexts a cross-cutting concern which can be modeled as domain-specificaspects. Such aspects allow for adapted join points for eventproduction or event consumption and can provide a con-cise mechanism for events to carry contextual informationwith them to guide the application of protocols, controlledthrough advice.

This paper addresses the problem of modular context rep-resentation and handling in object-oriented programminglanguages with support for explicit events. After illustratingthat the design of event contexts is a crosscutting concern indistributed systems through real-world examples, this papermakes the following technical contributions:

1. The design of domain-specific context aspects — con-spects for short — to modularize the design and im-plementation of event contexts. Our proposed designis general, allowing any language with explicit events-based constructs to be extended to support conspects.

2. An implementation of conspects in EventJava [12] ontwo architectures including an embedded system witha real-time Java virtual machine.

3. An empirical evaluation of two applications: (a) anevent-based tornado monitoring application and (b) asoftware suite for mobile social networking, to demon-strate the performance benefits of using contexts tochoose different event dissemination protocols.

The remainder of this paper is structured as follows. Sec-tion 2 presents background on explicit events and event con-texts. Section 3 outlines features of conspects. Section 4presents their implementation in EventJava. Sections 5 and6 present the tornado monitoring and mobile social network-ing case studies respectively. Section 8 presents related workand Section 9 concludes with final remarks.

2. BACKGROUND AND MOTIVATIONIn this section we outline the core abstractions of dis-

tributed event-based programming underlying EventJava [12],and illustrate the need for specific support for event contextthrough a tornado monitoring application. In tornado mon-itoring, several natural events are measured in order to pro-duce a valid representation of ongoing weather conditions.Horizontal wind velocity and cloud motion are examples ofsuch events which are used to derive different indicators, oneof which is Storm Relative Helicity (SRH) [32]. The appli-cation is further analyzed and elaborated in Section 6.

2.1 Event MethodsAn application event type is implicitly defined in Event-

Java by declaring an event method, a special kind of asyn-chronous instance-level method. This is similar to otherobject-oriented programming languages with support for ex-plicit events (e.g., JoinJava [21], Cω [3], SCHOOL [8]).

2.1.1 Event definitions and productionThe formal arguments of an event method correspond to

the (explicit) attributes of the event type. For example,the signature hVelocity(float veloc, float alt) defines the type

of horizontal wind velocity events. The types of event at-tributes (event method arguments) are restricted to primi-tive or serializable types or remote references to ensure thatthey can be passed over the wire. An event method declara-tion is preceded by the event keyword, which differentiatesbetween a regular, synchronous, method with void returntype and an asynchronous event method. For instance, aninterface TornadoMonitor could declare a hVelocity event anda cMotion event as follows:

interface TornadoMonitor {event hVelocity(float velocity, float altitude);event cMotion(float motion, float altitude);}

EventJava supports the notification of an event to an in-dividual object (unicast, 1-to-1) simply by invocation of thecorresponding event method on that object. For example,a horizontal wind velocity event can be notified to an in-stance m of TornadoMonitor simply as m.hVelocity(...). In-vokers are not blocked upon event method invocation butproceed asynchronously.

EventJava further supports implicit multicast (1-to-many)interaction by reusing notation from static methods. Forexample TornadoMonitor.hVelocity(...) dispatches the eventto all objects conforming to TornadoMonitor (and subtypes)within confines specified at construction of respective ob-jects. While EventJava supports more explicitly closed mul-ticast groups or point-to-point (1-of -many) communicationthrough specific proxies, we focus on the former multicaststyle for its brevity.

The same kind of multicast call can be made on any classC implementing TornadoMonitor, limiting the event to allinstances of C and its sub-classes. Note that we use the termmulticast rather than broadcast, as the delivery of the eventto a particular object will always be subject to any guards onthat object as we will see shortly. Destinations of a multicastevent receive distinct copies of all event attributes.

2.1.2 Event handling and compositionThe easiest way to react to events is to implement respec-

tive events methods. Consider the class below:

class TornadoMonitorImpl implements TornadoMonitor {event hVelocity(float veloc, float alt, long time) {...}event cMotion(float motn, float alt, long time) {...}}

The class allows us to receive, individually, all hVelocityand cMotion events multicast as described above. By en-abling the handling of complex events rather than only in-dividual events, application components can be simplifiedand repetitive or spurious coordination, composition, andcommunication can be further avoided. In tornado moni-toring, horizontal wind velocity and cloud motion can forinstance be correlated to compute SRH. SRH measures, inpart, the changing of directions of winds among various al-titudes within a particular area relative to a storm. ClassTornadoMonitorImpl2 below joins events of the two types de-fined in interface TornadoMonitor:

class TornadoMonitorImpl2 implements TornadoMonitor {event hVelocity(float veloc, float alt, long time),

cMotion(float motn, float alt, long time) {...}}

Page 3: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

Such joins are expressed by comma-separated lists of eventmethod headers. The method body, referred to simply as re-action, is thus“shared”among the event method headers. Ina reaction, we must prefix the event attribute names by therespective event method names, e.g., hVelocity.alt/cMotion.alt, when ambiguities can otherwise arise. There is no im-plicit matching on homonymous attributes across events.

EventJava separates the expression of which events arecomposed from how they are composed by the use of guards.These are optional and their absence is interpreted as whentrue. We can extend the example above as follows

class TornadoMonitorImpl3 implements TornadoMonitor {event hVelocity(float veloc, float alt, long time),

cMotion(float motn, float alt, long time)when (horizontalVelocity.time < cloudMotion.time) {

float SRH = calculateSRH(veloc, motn);if(SRH >= 30 && SRH < 100) triggerAlert(”Weak”);if(SRH > =100 && SRH < 300) triggerAlert(”Mild”);if(SRH >= 300) triggerAlert(”Strong”);}}

to express a strategy consisting in reacting in three waysupon hVelocity events followed by cMotion events. A guardcan use regular Java operators for boolean expressions, suchas negation (!) or disjunction (||). The example is stronglysimplified for presentation. For instance, timestamps wouldin addition have to be within some range of each other.

Event windows in EventJava furthermore support the com-position of several events of the same type. Such windowsare syntactically unified with arrays. As an example, we candeclare a class TornadoMonitorImpl4 which composes streamsof events over a window size of 4 as follows:

class TornadoMonitorImpl4 implements TornadoMonitor {event hVelocity[4](float veloc, float alt, long time),

cMotion[4](float motn, float alt, long time){...}...}The attributes of an individual event can be indexed. For

example, hVelocity[2].veloc or simply veloc[2] represents theveloc value of the third instance of hVelocity (indices startat 0 just as in arrays). Event streams imply ordering, i.e.,for both event types above time[i]<time[i + 1] ∀i ∈ [0..2].

EventJava provides additional support for limited returnvalues, or synchronous handling (not invocation) throughan alternate queue keyword instead of event. These are notrelevant for the following and are thus omitted.

2.2 Event ContextsIn our tornado monitoring example, both horizontal ve-

locities and cloud motion events are timestamped.

2.2.1 TimeThe class TornadoMonitorImpl above assumed synchronized

physical clocks when verifying that hVelocity occurs beforecMotion. The problem with this class is that it mixes appli-cation logic with information which is specific to that onerepresentation of time. It cannot be deployed when sensorshave clocks which are not synchronized, which depends ondeployment, communication protocols, make, model, etc.

Selecting the appropriate representation of time is an im-portant and difficult task when developing distributed sys-tems. Relying on a too strong assumption (e.g. perfectly

synchronized clocks) can lead to violating safety propertiesand thus to inconsistencies if the assumption does not holdin practice. For instance, processes can be suspected to havefailed by some nodes but not by others. Inversely, an overlyweak notion of time can lead to inefficient programs. Takethe case of Lamport clocks [24], a lightweight approxima-tion of real time by logical time. Lamport clocks captureall actual causality relations among events, yet can lead tomany false positives, i.e., events which are considered to beordered while they are unrelated. When ordering eventsissued by different interacting processes based on a combi-nation of Lamport clocks with unique process identifiers tobreak ties, an event from a given process p with timestampl can only be handled by another process p′ once p′ hasreceived events with larger timestamps than l from all pro-cesses with smaller process identifiers than p [35]. This isclearly an inefficient solution which can be improved by Vec-tor clocks [25], but can be much more drastically improvedif synchronized clocks can be assumed (e.g. using NTP1)and/or the network is synchronous. Rewriting an applica-tion for every possible type of logical or physical time thatmight be encountered throughout testing and production de-ployments is clearly onerous, especially as different notionsof time also will imply different protocols (e.g. multicast).

2.2.2 Problem characterizationTime is an intrinsic attribute of events, present from their

creation, throughout their transmission, composition, andhandling. But the definition of time for events is only aninstance of a general problem, namely that of defining theircontexts. In modern mobile location-sensitive communica-tion scenarios, the origin of an event may for instance be asrelevant as their time of birth. As with time, such a spacedimension can be physical (based on GPS, Galileo, RFIDetc.) or logical (within a given building, room; based onidentifier of node, process, object, thread, class etc.). Manymore application-specific dimensions exist, such as a proof ofauthenticity (enforcing security policies), history (for debug-ging or audit), or confidence level (dealing with uncertainty).

Even if some context dimensions can be specific to familiesof applications, it is desirable to separate contexts from basecode as their exact implementations might vary across appli-cations or deployments the same way they might be shared.At the same time, a library approach is unsatisfactory as itdoes not allow for verifying consistent uses of contexts. Forinstance, when correlating events of different types, theseshould have comparable contexts. Furthermore, many ac-tions for creating or handling context might be repetitive.In short, contexts are a cross-cutting concern of event-basedapplications. We thus propose domain-specific aspects forimplementing these in EventJava .

3. CONTEXT ASPECTSThis section outlines the design of conspects — context

aspects for event-based distributed programming — firstthrough the tornado monitoring example, and then throughan example from mobile social networking.

3.1 Model OverviewWe introduce first-class contexts, which resemble classes

1http://en.wikipedia.org/wiki/Network_Time_Protocol

Page 4: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

in that they can declare fields and methods. The former rep-resent the implicit attributes that are associated with eventsto which the given context applies. The latter are predicatesthat are used in guards, or are used for refactoring codeused in advice. Advice distinguishes contexts from classesand comes in four types with specific join points for describ-ing their use and manipulation in the creation and handlingphases of the events they apply to. Contexts are also respon-sible for selecting protocols for the respective phases. Belowwe further elaborate on these notions. We support singleinheritance for contexts, but a unique context must exist foreach event at every program point. When comparing twoevents during event correlation, we require that contexts becompatible, i.e., that the context associated with the latterevent must be of a subtype of the former event’s context.

3.2 Context Fields and MethodsContexts are first-class constructs in EventJava, at the

same level as classes. A first characteristic of our contextaspects are context-specific fields, representing contextualattributes of events. More precisely, we separate the eventattributes/event method arguments presented in the previ-ous section into two kinds:

Explicit attributes denote application-defined event methodarguments which typically vary for every event type. Anexample is the velocity argument of the hVelocity eventsin the tornado monitoring application.

Implicit attributes constitute the context of an event. Wethus also refer to these simply as context attributes. Thecanonical example is time, illustrated by the tornado mon-itoring example.

With conspects, implicit attributes are extracted from theapplication into a context declaration. Implicit attributestypically are the same for entire components or applications,within deployments. Consider the following class:

class TornadoMonitorImpl5 implements TornadoMonitor {event hVelocity(float veloc, float alt),

cMotion(float mtn, float alt)when (hVelocity < cMotion) {...}}

This class only contains the application logic to manipu-late hVelocity and cMotion events. The time aspect of eventsis abstracted, and captured by the PhysicalClock context out-lined in Figure 1. Such a declaration looks similar to a classdeclaration, but starts by the context keyword. The timeattribute can be viewed as a “field” of the context. Let usfocus on the context attributes and methods for now.

The comparison expressed previously on the time attribute(hVelocity.time < cMotion.time) is now expressed on the event(names) themselves: hVelocity < cMotion. This comparisonis translated to an “invocation” of ”<” in the PhysicalClockconspect. The quotes are necessary because the method

name is an operator in this case. While a comparison oftwo events on ordering is most commonly interpreted as re-lating to their logical or physical time of creation, any con-text attributes could be used for such a comparison withconspects. Consider the alternative context LogicalClock inFigure 1, where class VectorClock is a standard implementa-

context PhysicalClock {long time;boolean ”<”(PhysicalClock c){ return (time < c.time); }

publish TornadoMonitor.hVelocity(..) ||TornadoMonitor.cMotion(..) {time = System.currentTimeMillis();with ReliableBroadcast(..)[time];}...}

context LogicalClock {VectorClock vc;boolean ”<”(LogicalClock vc1){ return (vc.compareTo(vc1) < 0); }

publish TornadoMonitor.hVelocity(..) ||TornadoMonitor.cMotion(..) {with VCCausalBroadcast(..)[..];}...}

Figure 1: Two different timestamp contexts: physi-cal clocks vs. logical (vector) clocks

tion2 of vector clocks [25]. This context can be substitutedfor PhysicalClock without changes to the application.

In general, conspects may define any number of methodswhich can be used in guards. These methods can refer to theattributes of the context via the thiscontext keyword. Justlike the standard this keyword, thiscontext can be omittedwhen disambiguation is not necessary. Context methods cor-respond typically to binary methods, i.e., they take a secondcontext of same type as argument, and are used in guardsin an infix notation. For example, equivalence verificationof two contexts could be implemented as follows:

context EqualityContext {...boolean equals(EqualityContext other) {...}}

A guard could then simply compare two correlated eventse1 and e2 making use of that context as follows:

event e1(...), e2(...) when (e1 equals e2) {...}

Context methods are not necessarily binary methods. Ad-ditional arguments can be added after the counterpart con-text argument; these have to be instantiated in the guardin that case. Suppose we wanted to verify whether a givenevent occurred within a given range of another event. Tothat end, we can define the following simple conspect:

context LocationContext {...Location loc;boolean within(LocationContext other, Range rng) {...}}

2E.g. http://project-voldemort.com/javadoc/all/voldemort/versioning/VectorClock.html.

Page 5: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

A guard could then simply compare two events e1 and e2

making use of that context as follows:

event e1(...), e2(...)when (e1 within(new Range(20)) e2) {...}

Context methods need not define a context argument,they can also relate to a single event. Context methodsare declared in contexts and not for example in the applica-tion logic to increase cohesion and decoupling of applicationlogic from contexts. Note that contexts can also define localmethods which are used in context advice explained shortly.

3.3 Context Creation and HandlingAs mentioned, one of the motivations for separating con-

texts from application code is to isolate and regroup con-text creation and handling operations and to avoid repet-itive code. Typically, in the tornado monitoring examplewith hardwired physical clocks, any event creation wouldhave to inquire the system clock through a method invoca-tion like System.currentTimeMillis(...) and pass the obtainedvalue for the time argument when issuing an event. This isstill a relatively simple single operation, but in other cases,this instantiation can be more complex. Many operationson or with event contexts tend to be specific to the contextattributes and also highly repetitive.

To isolate and regroup such code, conspects include fourspecific categories of event handling advice:

send is executed after a unicast event is produced but beforeit is sent.

publish is executed after a multicast event is produced butbefore it is multicast.

receive is executed after an event is received but before it ismatched to any pattern.

consume is executed after an event is matched to a patternbut before it is consumed by a reaction.

As alluded to above, these advice are always executedat a very specific moment with respect to the event han-dling path. Their exact places of application are outlined bypointcuts which are rather simple in their structure. Moreprecisely, there are only two types of elementary join points,namely such (a) denoting the event types that the advice(with the respective context) applies to and those (b) rep-resenting the locus of application. For example, a join pointC.e in C′ in the case of a publish advice means that anyevent multicast C.e(...) which occurs in class C′ will be ad-vised by the respective advice. In the case of a receive orconsume advice, the same join point will imply that the ad-vice is executed every time an instance of C.e is matched foran instance of a class C′, implying that C′ is a subtype ofC. In the same scenario, C′.e in C′ means that only multi-casts of e on C′ or subclasses of C′ will be advised, and C′.eapplies to all classes.

Consider the examples of Figure 1. In both contexts,we detail publish advice that are executed upon multicas-ting of hVelocity and cMotion events defined in the body ofthe TornadoMonitorImpl5 class. The “..” notation for the ex-plicit event attributes means that the advice will not reador modify those. (Note that this concrete two dots syntaxis distinct from the three dots used to indicate the omissionof details for presentation simplicity.) The last line in the

case of the physical clocks (with ReliableBroadcast(..)[time];)means that the time attribute is created by the advice, andthat the event will be passed to a protocol called “Reliable-Broadcast”. The remaining arguments of the event methodinvocation are passed on without changes. The correspond-ing line in the case of the logical clocks indicates that thecontext attribute(s) will be created by the protocol layer – inthis case “VCCausalBroadcast”. These protocol invocationsare transformed to calls to specific APIs, outlined shortly.

In terms of control flow, all advice types have the samesemantics. Each advice is executed at a particular pointof the event handling path, but it must explicitly invoke aprotocol for the actual handling of that respective part in adedicated with clause. That is, the advice can choose not toinvoke such a protocol but that means that the event willnot be passed on. Different protocols can be selected by asame advice. Consider the example of physical and vectorclocks. Both publish advice invoke a broadcast protocol.These protocols must be bound at runtime for the advice towork properly. Furthermore, several with clauses can appearin a same advice, which allow protocols to be switched atruntime. Table 1 presents an overview of our four advicetypes and their duties/the protocols they invoke along withexamples. A default protocol exists for each of these phases.It is invoked as with Default(..)[..];. This default protocolis similar in nature to the proceed keyword used in aroundadvice of AspectJ, except that, as mentioned, a protocolinvocation in conspects is mandatory for the event to behandled further. Just like proceed, such an invocation canbe both headed and followed by further statements. Sinceevent handling is asynchronous, there is however never areturn value for any of the advice.

ProtocolAdvice type Protocol and library examples

invoked

send Unicast TCP/IP, UDP, Java RMI, MPI

publish MulticastMultisend, Reliable Broadcast,IP Multicast, JMS

receive Matching First received, most recent, Jess

consumeThreading

Single thread per object, threadpool (thread per pattern, threadper reaction)

Table 1: Overview of event instantiation and han-dling advice types and examples in conspects.

It is important to note that the send and publish adviceplay the role of “constructors” for contexts. They are re-sponsible for ensuring that context attributes are initialized,though the use of initializers coupled directly with attributedeclarations can simplify this task. In the physical clockexample, we could have declared the timestamp as follows

context PhysicalClock2 {long time = System.currentTimeMillis();...}

leading to the same semantics as in Figure 1. This initial-ization constraint is necessary to keep in mind when usinglocal context methods, i.e., refactoring code used in contextadvice into context methods. In an advice of types receiveor consume one can assume that the attributes of a context

Page 6: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

have been initialized by either a preceding send or publishadvice. An attribute which is always present in all advicesis this, which refers to the actual object which is issuing theevent (send or publish advice) or potentially consuming it(receive or consume). Its value is null in the former case ifthe event is created within a static method.

3.4 Mobile Social Networking ExampleWe showcase conspects through another example, this

time chosen from the domain of mobile social networking todemonstrate other than time dimensions of event contexts.

3.4.1 Simple location-based publish/subscribeThe Friend Finder application is used to be informed

when friends are nearby. Figure 2 presents an excerpt ofthe application code using EventJava and conspects. Forsimplicity, we omit the membership management, i.e., howusers originally get acquainted and connected, and use a sim-ple multicast on class SimpleFriendFinder. Quite obviouslya multicast will be limited to validated contacts. myStatusis obtained from a graphical user interface (GUI), whereasmyName is stored as part of the configuration of the appli-cation. Status updates are sent periodically (every 5000 ms)here, but they could also be initiated by the GUI.

class SimpleFriendFinder implements ... {String myStatus;String myName;...void run(){

while(true){Thread.sleep(5000);SimpleFriendFinder.statusEvent(myStatus, myName)}}event statusEvent(String status, String Name){

when(status == ”available”) {myGUI.alert(Name + ” status: ” + status);

}}

context SimpleLocationbasedPubSub {Location loc = Location.currentLocation();...publish SimpleFriendFinder.statusEvent(..) {

with LPSSHybrid(..)[..];}receive SimpleFriendFinder.statusEvent(..) {

if (Location.inRange(loc, new MeterRange(250),Location.currentLocation()))

with LPSSMatcher(..)[..];}consume SimpleFriendFinder.statusEvent(..) {

with SingleThreader(..)[..];}}

Figure 2: Simple Friend Finder using EventJava

The SimpleLocationbasedPubSub context here uses a spe-cific multicast protocol (LPSSHybrid) which we will elaborate

on more in Section 6, and a specific matcher (omitted forbrevity) which is rather trivial as the implemented location-based publish/subscribe model does not usually provide ad-vanced correlation features. More interesting in the receiveadvice is that an event is only passed to the matcher if it waspublished in a location within a given range (250 meters) ofthe location of the receiving device at that time. The ex-ample alludes to a single-threaded delivery model; that is,there will be one thread per SimpleFriendFinder object han-dling statusEvents.

publication space subscription space

receiversendertransmission range

location-based match

Figure 3: Location-based publish/subscribe

3.4.2 Advanced featuresThe outlined example corresponds to a location-based pub-

lish/subscribe as described by Meier and Cahill [26]. Alter-native models associate a time-to-live (TTL) property withevery event, or restrict location-based matches, as illustratedin Figure 3, by associating also a publication range withevents (delineating a publication space around the publish-ing device) in addition to a subscription range as above (de-scribing a subscription space). With the publisher devicecontinuously moving, the publisher location can be updatedon events that have been multicast already. With TTL andpublication ranges, a multicast event resembles a satelliteorbiting the publisher.

Figure 4 outlines a solution in EventJava which incorpo-rates all these features. In addition it allows publicationranges and TTL values to be set individually for each event.These are hardwired in the example still for brevity, butillustrate the possibility of specifying context attributes ex-plicitly in the application, if supported by a correspondingpublish advice. That is, the publish advice defined in con-text LocationbasedPubSub specifies that the range and TTLattributes are defined by the application. Conspects sup-port overloading of advice with different sets of application-defined context attributes and join points.

The inRange predicate verifies that both the publisher andthe subscriber are within the respective ranges of each other.Classes LPSSHybrid and LPSSMatcher implement APIs pre-scribed for implementations of protocols that are to be calledfrom publish (as well as send) and from receive advice re-spectively. These APIs will be further discussed in the nextsection. In addition to implementing the Substrate interface,the LPSSHybrid class is responsible for periodically monitor-ing the current location of a device and sending positionupdates. Upon reception of such updates for a given object,the class is in charge of updating the LPSSMatcher, whichupdates any events from the corresponding sender that ithas previously received (through add). The matcher is alsoresponsible for verifying the TTL of events.

4. IMPLEMENTATIONThis section outlines the implementation of conspects.

Page 7: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

class FriendFinder implements ... {String myStatus;String myName;Range myRange;...void run(){

while(true){Thread.sleep(5000);FriendFinder.statusEvent(myStatus,

myName)[new MeterRange(200), 10000]}}event statusEvent(String status, String Name)

when(status == ”available” && inRange(myRange)) {myGUI.alert(Name + ” status: ” + status);

}}

context LocationbasedPubSub {long time;Location loc;Range range;long TTL;Object sender;...boolean inRange(Range r) {

return Location.inRange(Location.currentLocation(), r)&& Location.currentLocation().inRange(loc, range);

}publish FriendFinder.statusEvent(..)[range, TTL] {

time = System.currentTimeMillis();loc = Location.currentLocation();sender = this;with LPSSHybrid(..)[time, loc, range, TTL, sender];}receive FriendFinder.statusEvent(..) {

if (System.currentTimeMillis() < time + TTL)with LPSSMatcher(..)[..];

}consume FriendFinder.statusEvent(..) {

if (System.currentTimeMillis() < time + TTL)with SingleThreader(..)[..];

}}

class LPSSHybrid implements Substrate ... {void multicast(Event ev, Context ctxt) {...}void subscribe(EventReceiver recv) {...}...}

class LPSSMatcher implements Matcher ... {void add(Event ev, Context ctxt) {...}...void updateLocation(Object sender) {...}}

Figure 4: Friend Finder with constrained publica-tion lifetime and spaces using EventJava

4.1 WeavingWe have implemented conspects as an extension to the

EventJava compiler [12] which uses the Polyglot extensiblecompiler framework [28]. In short, the compiler generatesa Java class for each context declaration, as a subtype of aroot Context class. The EventJava compiler generates codefor the production, reification, multicast, reception, and fil-tering of events and the dispatching of reactions. In contrastto contexts, events are transformed to a generic representa-tion with class Event outlined in Figure 6 since they do notinvolve methods. The compile-time weaver inserts contextarguments into event methods, and complements these byrespective methods with normalized arguments (only Event)and adds advice at the appropriate points.

A post-compile weaver for conspects using the ASM 2.0bytecode manipulation framework to analyze and instru-ment compiled EventJava programs is underway.3

4.2 Runtime FrameworkTo provide the proposed features, the implementation of

conspects is strongly intertwined with the runtime frame-work underlying EventJava. Figure 5 presents a high-levelview of this framework and illustrates where/how advice areapplied. An event notification is passed to the communica-tion substrate which takes care of remote communicationincluding unicast and multicast. In the multicast case, thesubstrate delivers all the serialized event method invocationsto the resolver, which determines the classes on which themethods were invoked and interacts with multicast objectsfor those classes. Multicast objects deliver the events to theevent handling objects, from where they are passed to thematcher (one instance per object) where they are typicallybut not necessarily stored in event queues. The matcheris responsible for checking the stored events for completedcomplex events. An identified match is passed to the handlerwhich incorporates a given threading model. The matchermay also incorporate a garbage collection policy or updateand replace stored events.

Resolver and multicast objects represent type-specific codewhich is generated at compilation to avoid costly calls throughthe Java reflection API. The substrate, matcher, and handlercomponents are defined as an API, with the main types be-ing Substrate, Matcher, and Handler respectively. Protocolinvocations in send/publish, receive, and consume advicecorrespond to subtypes of these respective API types. Moreprecisely, the call to“VCCausalBroadcast” in the publish ad-vice of Figure 1 will be transformed to a call to the multicastmethod outlined in Figure 6 in a class VCCausalBroadcastwhich implements the Substrate interface. The marshallingof the context attributes into an instance of the respectivecontext class, and of that object together with the event at-tributes into an instance of Event is done by weaver-generatedcode as mentioned earlier. The same approach is applied formatchers and handlers. Due to space restrictions, Figure 6only outlines the Substrate and Matcher interfaces. Note-worthy in the former interface is the introduction of filterswhich are constructed at compilation from the predicates– one for each correlation pattern. Such a filter follows anSQL-like syntax similar to the selectors of JMS [20], and

3An extended version of this report contains a pre-liminary overhead assessment of postcompiler weav-ing http://www.cs.purdue.edu/homes/peugster/EventJava/Conspects.pdf.

Page 8: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

describes all conditions of a guard based solely on event at-tribute comparisons. These filters can be optionally used bya smart substrate to perform message filtering throughoutthe network [16]. Conversely, Matcher allows the consumerobject to be connected to it as a Guardian. The latter in-terface allows application-specific guards to be invoked in ageneric manner from the matcher. The code implementingthis interface is generated automatically.

context VContext { publish C.e(..) in C' { c1 = ... ... cn = ... with XMulticast(..)[c1...cn]; }}

Sink

Substrate

Handler

eEventReceiver r = ...;r.deliver(e)

ZHandler h = h.react(...)

Source

receive C.e (..)[..] { ... with YMatcher(..)[..] }

YMatcher m = ...;m.add(e)

Matcher

EventAttributes Patterns

ContextualAttributes

Event Store

XMulticast m = (...);m.multicast(e)

VContext c = new VContext(...);Event e = new Event("C.e",c,v1,...,vn,c);

Event ProductionC.e(v1,v2,...,vm);

consume C.e (..)[..] { ... with ZHandler(..)[..] }

Network

Guard Evaluationc.guard("C.e",v1,...,vm,c1,...,cn);

C c = ...;

Reactionc.eval("C.e",v1,...,vm,c1,...,cn);

Figure 5: The EventJava runtime framework. Sinksare objects invoking event methods; sources are in-vokees. Red represents code generated from and forconspects. Blue represents the path of the event inthe application class including in code generated bythe EventJava compiler. For simplicity the figurefocuses on dispatching of single events.

4.3 Fiji Virtual MachineWe ported the EventJava compiler to execute with the

Fiji VM4 which is an ahead-of-time compiler that trans-forms Java bytecode into fast ANSI C code and which runsEventJava code. Thus it runs on any platform that hasa C compiler, threads, and locks. Supported platforms in-clude Linux, Darwin, NetBSD, RTEMS, x86, PowerPC, andLEON. A noteworthy feature of Fiji VM is its ability to runin very restricted real-time embedded microkernels such asthe real time executive for multiprocessor systems (RTEMS) [5].RTEMS is used for very hard safety-critical tasks, includingboth ESA and NASA missions.

Fiji VM supports priority-aware locking and real-time pri-orities for threads, and takes care not to use any unpre-dictable operating system facilities, like OS-provided dy-namic memory allocation, except inside library calls. Ad-ditionally, Fiji VM employs a variety of techniques, detailedin [29], for ensuring that the generated C code obeys Javasemantics, and permits accurate stack maps for scanning by

4http://www.fiji-systems.com.

public class Event implements Serializable {public String classN,public String eventN;public Context ctxt;public Object[] args;public Event(String typeN, Context c,

Object ... args) {...}...}

public interface Substrate {public void unicast(Remote sink, Event ev);public void multicast(Event ev);public void join(String typeN, EventReceiver recv,

String[] filters);public void leave(String typeN, EventReceiver recv);...}

public interface Matcher {public void add(Event ev);public void connect(Guardian guard);...}

Figure 6: Excerpt of API for the EventJava con-spects framework

the garbage collector. Fiji VM currently utilizes an Immix-style [4] on-the-fly concurrent real-time garbage collector.

Although the Fiji VM supports GNU classpath, the stan-dard Java libraries are typically too big for resource con-strained embedded systems. The Fiji VM provides a smallerlibrary, similar in scope and size to Java ME, called FijiCore. We ported the EventJava compiler to work with FijiCore. Additionally, since the Fiji VM is targeted at hardreal-time systems it does not support dynamic classloadingnor reflection on classes that cannot be statically resolvedusing class hierarchy analysis. Since EventJava and ourconspects were carefully designed not to rely on such fea-tures, we were able to easily deploy in such a hard, resource-constrained environment.

5. CASE STUDY – TORNADO MONITORIn this section, using a tornado monitoring application, we

illustrate the benefits of conspects by using them to switchbetween protocols without affecting the base program.

5.1 Tornado Monitoring ApplicationWe use real-world complex events derived from NOAA’s

WDSS-II tornado monitoring system.5 The system con-sists of a distributed tornado detection algorithm (WSR-88FTVS6) with several components deployed over different ex-ecution environments. Each component is tasked with pro-cessing a different set of events. The deployment architec-ture contains wireless field sensors over a large geographicalarea, each measuring atmospheric parameters like wind ve-locity, direction, air temperature and pressure. Wired base

5http://www.nssl.noaa.gov/divisions/warning/swat/wdssii.php6http://www.nssl.noaa.gov/divisions/warning/swat/tda.php

Page 9: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

(a) Network diagram for the throughputexperiments.

0

5000

10000

15000

20000

25000

0 5 10 15 20

Throughp

ut(e

vents/s)

#of(x86)nodes

CausalOrderBroadcastwithVectorClocks

CausalOrderBroadcastwithoutVectorClocks

ReliableBroadcast

(b) Throughput (events/sec) on x86.

0

5000

10000

15000

20000

25000

0 1 2 3 4 5 6 7

Throughp

ut(e

vents/sec)

#ofLEONboards

CausalOrderBroadcastwithVectorClocks

CausalOrderBroadcastwithoutVectorClocks

ReliableBroadcast

(c) Throughput (events/sec) on LEONGR-XC3S-1500.

Figure 7: Event processing throughput (events/sec) of the tornado monitor benchmark using three differentevent dissemination protocols

stations communicate with the field sensors as well as otherneighboring base stations to consume and process weather-related events, thereby providing real-time tornado informa-tion. Each base station calculates several parameters likeSRH, Convective Available Potential Energy (CAPE) andEnergy Helicity Index (EHI). SRH is calculated by corre-lating streams of horizontal wind velocity and cloud motionevents, CAPE by correlating streams of air parcel temper-ature and ambient temperature. EHI is calculated first byfinding the product of the SRH and the CAPE for a re-gion, then the product is divided by a threshold CAPE. Forevaluating the event processing throughput of our imple-mentation, we consider 4 producers (producing the variouswind speed, temperature and cloud motion events) and 6-16consumers as described below in Section 5.3.

5.2 Communication ProtocolsIn our experiments, events were disseminated using three

reliable communication protocols implemented on top of UDP:

Reliable Broadcast: Clocks are synchronized and thus thebroadcast protocol does not need to deal with ordering.Events are delivered based on their timestamps.

Vector Clock-based Causal Order Broadcast: Causal Or-der Broadcast ensures that messages (events) are deliv-ered respecting cause-effect relations, thus preserving real-time relations essential for consistency. Causal OrderBroadcast can be implemented with vector clocks (seeSection 3). The use of vector clocks is enabled by ourevent contexts in this benchmark.

History-based Causal Order Broadcast: In this proto-col, every multicast event carries a history of the eventspreviously delivered by its source, and no process deliv-ers an event before it delivered all antecedents. By usingUniform Reliable Broadcast, histories can be reduced toidentifiers which in practice can be pruned regularly.

Vector Clock-based Causal Order Broadcast is preferableover History-based Causal Order Broadcast for small sys-tems with high production rates. With low production ratesand scarce network resources the latter might be favorable.

5.3 Experimental SetupThe event processing throughput of our implementation

was evaluated using two different execution environments.

The first was a 16 node cluster of Dell workstations, eachwith a Xeon 3.2GHz dual-core processor and 2 GB of RAMrunning Linux. The cluster was divided into one producerand 17 consumers. To adequately test our conspects in re-source constrained environments, such as sensor networks,we utilize the combination of the Fiji VM + RTEMS to cre-ate realistic embedded scenarios in a 6-board cluster of GR-XC3S-1500 LEON development boards. Each board’s XilinxSpartan3-1500 field programmable gate array was flashedwith a LEON3 configuration running at 40Mhz with 8MBFlash PROM and 64MB of PC133 SDRAM. This environ-ment is outlined in Figure 7(a).

5.4 ResultsFigures 7(b) and 7(c) show that the throughput of the tor-

nado monitor application varies significantly with the choiceof dissemination protocol. The presence of synchronizedclocks yields the execution environment with strongest guar-antees, throughput is consequently the highest with ReliableBroadcast. In the absence of synchronized clocks, typical ina distributed system, Causal Order Braodcast has to be usedto compare two events. Figure 7(b) shows that the through-put of History-based Causal Order Broadcast (without vec-tor clocks) is extremely low and degrades quickly. UsingCausal Order Broadcast with vector clocks in event contextsincreases the throughput on our workstation configurationby a factor of 5x in the presence of 8 consumers and by afactor of 40x in the presence of 16 consumers. Figure 7(c)shows that the use of vector clocks increases the throughputon the LEON GR-XC3S-1500 board by a factor of 3.3x inthe presence of 6 consumers.

6. CASE STUDY – SOCIAL NETWORKINGIn this case study, we investigate three communication

(event dissemination) strategies in four different social ap-plications running on a mobile ad hoc network. We showthat choosing the optimal communication strategy can sig-nificantly improve performance in terms of message load.

6.1 Social Networking ApplicationsWe evaluate the following application scenarios7:

• The Polling application can be used at conferences bypresenters to gather votes from all participants located

7Cf. SpotMe www.spotme.com.

Page 10: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

in a room during their talk. Participants typically re-ceive an invitation to reply to certain questions.

• The Friend Finder application, which we used as ex-ample in Section 3, allows people to be notified of thepresence of nearby friends. We evaluate two settingsof the application, the first one with 30 users (FF1)and the second one with 300 users (FF2).

• The Search application is used by conference partici-pants who want to be notified when a participant witha certain profile (e.g. name, activity, interest) comeswithin a certain proximity.

• The Advertisement application is the last scenario weinvestigate. As mentioned above, shoppers are notifiedwhen nearby shoppers have offers of interest for them.

6.2 Communication ProtocolsWe use conspects to switch between three location-based

publish/subscribe (LPSS) protocols to match events basedon their content and disseminate them to interested receiversin a defined range. First, the LPSSMessageCentric protocol,which disseminates events along with contextual informationin a defined range and performs matching on the receiverside. Second, the LPSSQueryCentric protocol, which relies onthe propagation of queries and location criteria of receiversin a defined range to allow senders to perform the matchingand initiate the routing of events. Third, the LPSSHybridprotocol, where both events and queries are broadcast upto a half the radius of the defined range and events arerouted to receivers outside of this shortened radius. Eachof these strategies can outperform the others depending onthe communication pattern of the application scenario (e.g.number of publishers and subscribers, ratio between publi-cations and subscribers).

6.3 Experimental SetupWe use a 500 meter-wide geographical field on which nodes

evolve. The field is populated by 300 nodes which includereceivers, senders and passive nodes that are running the ap-plication. Each node has WiFi capabilities with a transmis-sion range of 50 meters. In order to simulate mobility we usethe Random Waypoint (RWP) mobility model with walkingspeed (2-3 m/s).8 We set a 5 second refresh rate, which in-dicates the time-span after which all persistent messages orall queries are re-broadcast in the message- or query-centricstrategies respectively. We ran simulations with durationsbetween 100 and 6000 seconds depending on the scenario.Parameters specific to each application are presented in Ta-ble 2: the number of senders and the number of receivers, aswell as the percentage of events matching in content and therelevant range which defines the proximity filter that senderand receiver must satisfy in order for receivers to receiveevents. Regarding this last parameter, two different valuesare evaluated, a 125 meter range and a 250 meter range.

8RWP has then criticized [40] in the past for exhibiting ahigh concentration of nodes at the field center of the fieldand for unrealistic movement patterns. To address the firstissue, we use a torus shaped map. For the second issue weconsider that people moving in an open field constitutes oneof the closest real-life scenarios for RWP.

Senders Receivers Cont. Match Range

Poll 300 1 100% 125, 250mSearch 300 30 10% 125, 250mFF1 30 30 100% 125, 250mFF2 300 300 100% 125, 250mAds 30 300 100% 125, 250m

Table 2: Scenario specific parameters

6.4 ResultsThe simulations presented hereafter were executed using

the Sinalgo9 network simulator, which is specifically designedfor protocol simulations in wireless networks. Sinalgo re-places sockets to simulate nodes communicating wirelesslyin an ad hoc network but runs on a standard Java VM. Fig-ures 8 summarize the results of the three communicationstrategies for the location-based publish/subscribe servicein the context of the previously described scenarios. Thesecomparative results show the message load generated byeach strategy in percentage points compared to the LPSSHy-brid protocol at the end of the simulation. These ratios areexpected to remain the same for longer simulations. Notethat the delivery ratio of all simulations are comparable.

Poll Lo

catio

n m

atch

25

0 m

rang

eFF1 FF2Search Advertisement

LPSSMessageCentric LPSSHybrid LPSSQueryCentric

Loca

tion

mat

ch

125

m ra

nge

0

100

200

300

400400

200

0 0

75

150

225

300300

150

0 0

100

200

300

400400

200

0 0

48

95

143

190200

100

0 0

100

200

300

400400

200

0

0

75

150

225

300300

150

00

50

100

150

200200

100

00

100

200

300

400400

200

00

100

200

300

400400

200

00

100

200

300

400400

200

0

Figure 8: Message load in percent – Hybrid = 100%

Polling: Here, results show that the LPSSQueryCentric pro-tocol outperforms the others in terms of message load.On one hand, the LPSSHybrid protocol is outperformedby a factor between 10 and 20 by the LPSSQueryCentricprotocol. On the other hand, LPSSMessageCentric proto-col is outperformed by a factor between 3 and 4 by theLPSSHybrid protocol. Hence the difference between thebest and the worst strategy is a factor 50.

Search: Here, results show that the LPSSQueryCentric proto-col outperforms the other two. The LPSSHybrid protocolis outperformed by a factor 2,5. The LPSSMessageCentricprotocol is outperformed by a factor between 3 and 3,5by the LPSSHybrid protocol. Hence the difference betweenthe best and the worst strategy is around a factor 8.

Friend Finder I: In this application, we consider 30 partici-pants interested in receiving notifications from each other

9http://dcg.ethz.ch/projects/sinalgo/.

Page 11: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

when they are nearby. The LPSSHybrid protocol outper-forms the LPSSMessageCentric protocol by a factor of 1,5and the LPSSQueryCentric protocol by a factor of 2.

Friend Finder II: In this application, where we consider all300 nodes as part of the friend list, the results showthat the LPSSHybrid protocol and the LPSSMessageCen-tric protocol are close, each one beating the other by 20%.The LPSSQueryCentric protocol is outperformed by a fac-tor between 2 and 4.

Advertisement: Here, 30 publications are sent to all nodesare interested in such messages, we consider that all shop-per eventually pass in front of the different shops and areinterested in receiving their offers. Here, the LPSSMes-sageCentric protocol is the most efficient in terms of mes-sage load. The LPSSHybrid protocol comes in second withbetween 3 and 4 times more messages, nevertheless itoutperforms the query-centric by a factor 3,5. Hence,the LPSSQueryCentric protocol is outperformed by theLPSSMessageCentric protocol by a factor between 10 and 12.

As stated previously, no strategy outperforms all othersin every scenario. Each strategy can demonstrate its su-periority in a certain real life setting. The quantificationof the differences between the message loads achieved forthe different scenarios advocates for the usage of an opti-mal strategy if the communication pattern can be inferredin advance. If this not the case or if the communication pat-terns vary strongly, the LPSSHybrid protocol can be used asa safe, though not always optimal, solution, since it is neverthe worst of the three strategies. With conspects protocolscan be switched even upon workload variations.

7. OVERHEAD OF POST-COMPILE WEAV-ING AND SCALABILITY OF CEJ

Our aspects can advise event production and consump-tion effectively. In consume advice, a programmer can addadditional predicates on fields of the context. In an event-based programming language with correlation patterns, us-ing compile-time aspect weaving merges all predicates oncontext fields and event method arguments in the matchercomponent (that matches events to correlation patterns). Ifpost-compile weaving is used, two matcher components aregenerated, one to evaluate predicates on context fields, andanother to evaluate those on event method arguments. Thiscreates a performance overhead – a decrease in the through-put per node due to the modularization that occurs withconspects. We measure this overhead by varying differentprogram parameters:

1. Total number of different event methods involved inthe application: Figure 9(a) shows that the overhead(decrease in throughput) is between 6.8% and 8.2%.The overhead increases slightly as the number of eventmethods increases – by approximately 0.2% between50,000 event methods and 75,000 event methods andby approximately 0.5% between 75,000 event meth-ods and 100,000 event methods. The measurementsin Figure 9(a) uses four event methods per correlationpattern, and a stream consisting of 1 million randomlygenerated events. Overhead is measured every 20,000events.

2. Number of event methods per correlation pattern: Fig-ure 9(b) shows that the overhead is between 6.5% and7.4%. The overhead decreases slightly as the numberof predicates added increases – by approximately 0.3%between 4 and 8 methods per pattern and by approx-imately 0.5% between 8 and 12 methods per pattern.Measurements in Figure 9(b) are taken keeping thetotal number of event methods in the application con-stant at 100,000. Hence, if there are 4 event methodsper pattern, there are 25000 patterns. The numberof patterns in the decreases as the number of eventmethods per pattern increases, hence the decrease inoverhead.

3. Number of predicates added in the DSA: Figure 9(c)shows that the overhead varies between 7.4% and 8.25%.The overhead increases slightly as the number of pred-icates added increases – by approximately 0.3% be-tween 4 and 8 predicates and 0.4% between 8 and 12predicates. In these measurements, the total numberof event methods in the application and the numberof event methods per correlation pattern remain con-stant.

These experiments show that the overhead of using post-compile weaving is small and scales well when various pro-gram parameters change.

8. RELATED WORKThis section presents work closest related to our contexts

for event-based programming.

8.1 Context-Oriented ProgrammingContext-oriented programming (COP) [19] is a program-

ming paradigm which enables applications to modify theirbehaviors according to several dynamic program parame-ters. COP introduces the concept of layers, which modu-larize behavioral variations spread over several applicationmodules. In this programming paradigm, there are twotypes of method definitions, namely plain and layered [1].Layered methods consist of base methods containing context-independent code, and partial methods that contain context-dependent code. Layers can be dynamically activated bythe program, potentially based on conditions in the execu-tion environment, and can be easily composed. Base meth-ods are executed when no layers are active, whereas par-tial methods are executed in the order in which layers areactivated by the program. In COP side-effects generatedby context-sensitive dynamically activated layers are global.Tanter [39] addresses this problem by proposing contextualvalues, which are values that depend on the context in whichthey are accessed and modified. An extension of Schemewith support for programmer-specified (explicit) contextualvalues is described in [39]. COP and all context-oriented lan-guages mentioned above explore a completely new paradigmcompared to our notion of contexts which is more specific toexplicit event-based programming and pragmatic in its na-ture. For a more detailed description of COP, the reader isreferred to [19] and [1]. Some COP extensions/incarnationsare ContextS [18] for SmallTalk, or ContextJ [2] for Java.

8.2 Aspect-Oriented ProgrammingThe popular AspectJ [23] language contains a vast col-

lection of mechanisms, which can mimic some features of

Page 12: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

0

1

2

3

4

5

6

7

8

9

100000

200000

300000

400000

500000

600000

700000

800000

900000

1000000

Overhead(%)

#ofeventsinthestream

50keventtypes

75keventtypes

100keventtypes

(a) Overhead vs. total number of eventmethods.

6.4

6.6

6.8

7

7.2

7.4

7.6

0 200000 400000 600000 800000 1000000 1200000

Overhead

(%)

#ofeventsinthestream

4methodsperpa4ern 8methodsperpa4ern

12methodsperpa4ern

(b) Overhead vs. number of event meth-ods per correlation pattern.

7.3

7.4

7.5

7.6

7.7

7.8

7.9

8

8.1

8.2

8.3

0 200000 400000 600000 800000 10000001200000

Overhead(%

)

#ofeventsinthestream

4predicates 8predicates 12predicates

(c) Overhead vs. number of additionalpredicates.

Figure 9: Overhead (decrease in throughput) of post-compile aspect weaving. The X-axis shows the size ofthe event stream used in benchmarking. Figure 9(a) shows the of adding 4 additional predicates using aroundconsume vs. the total number of event methods in the application. Each pattern contained 4 events percorrelation pattern. Figure 9(b) shows the overhead of adding 4 additional predicates using around consumewhen the number of event methods per pattern varies. Figure 9(c) shows the overhead of adding additionalpredicates using around consume when the number of predicates added varies.

conspects. For example, by introducing naming and typ-ing conventions through compiler directives, AspectJ cansupport event methods. within pointcuts can determine theassociation between an event method call join point and thecontaining class, allowing for the context creation to occursimilarly to publish/send. Further conventions can be in-troduced on the event consumer side for the expression ofshared method bodies (reactions) or guards. Dynamic invo-cations through reflection can be used to unmarshal eventsreceived over the wire to trigger the corresponding methodinvocations. In general, AOP can be viewed as a form of im-plicit event-based programming as opposed to the explicitevents used herein, each of which have their advantages.

Event-based aspect-oriented programming (EAOP) [7] pro-vides a generic framework for the formal definition and inter-action analysis of stateful aspects, with aspect compositionand inter-crosscut pattern variables. Remote interaction isunfortunately not supported. Conversely, aspects with ex-plicit distribution (AWED) [27] support the remote moni-toring of distributed applications with remote pointcuts anddistributed advice.

8.3 Event-based ProgrammingMany programming languages support events explicitly

through some form of asynchronous methods or specific con-structs. Examples include ECO [16], Ptolemy [31], Ambi-entTalk [6], and JavaPS [10], or Actor-based languages andlanguage extensions such as Erlang [9] or Scala Actors [17].Most languages or language extensions with support for cor-relation, such as Polyphonic C# [3] (now integrated withCω) , JoinJava [21], or SCHOOL [8], and libraries such asfor Visual Basic [34], Erlang [30], or Scala [17] are based onthe Join Calculus [14]. CML [33] and other languages with-out inherent support for correlation rely on “staged” eventmatching where the consumption of a first event is a pre-condition for subsequent matching. These languages varyin subtle but important ways in their event representation(methods, objects, functions/function calls, etc.), address-

ing mechanism (unicast, multicast, broadcast), or in otherparts of their underlying models and implementations. Yetnone of these languages support modular expression of con-texts. Our own EventJava [12] was previously presentedwith a much more rudimentary model of contexts based onlibraries and program design conventions, detailed in [22].

9. CONCLUSIONProgramming pervasive systems is difficult as it requires

dealing with asynchrony, distribution, and heterogeneousenvironments. One of the central issues in such systemsis to decouple participants in time and space, as well asalong other dimensions. In this paper we presented domain-specific aspects called conspects for capturing event contextin modular way. We presented the semantics of these contextaspects and illustrated their usage through two pervasive ap-plications. We provided a detailed evaluation for the gainin performance that protocol switching based on conspectspermits in two real-world case studies corresponding to thoseapplications: a NOAA tornado monitoring application anda mobile social networking suite.

We are currently refining a static program analysis for ver-ifying context uniqueness for a given event, and are workingon post-compile weaving of conspects.

10. REFERENCES[1] M. Appeltauer, R. Hirschfeld, M. Haupt, J. Lincke,

and M. Perscheid. A Comparison of Context-orientedProgramming Languages. COP’09.

[2] M. Appeltauer, R. Hirschfeld, and H. Masuhara.Improving the Development of Context-dependentJava Applications with ContextJ. COP’09, pages 1–5.

[3] N. Benton, L. Cardelli, and C. Fournet. ModernConcurrency Abstractions for C#. TOPLAS,26(5):769–804, 2004.

[4] S.M. Blackburn and K.S. McKinley. Immix: aMark-Region Garbage Collector with Space Efficiency,

Page 13: Putting Events in Context - Purdue University · Putting Events in Context Aspects for Event-based Distributed Programming A. Holzer1 L. Ziarek2 K.R. Jayaram3 P. Eugster3 1LARIM,

Fast Collection, and Mutator Performance. PLDI’08,pages 22–32.

[5] OAR Corporation. Real-Time Executive forMultiprocessor Systems (RTEMS).http://www.rtems.org, 2009.

[6] J. Dedecker, T. Van Cutsem, S. Mostinckx,T. D’Hondt, and W. De Meuter. Ambient-OrientedProgramming in AmbientTalk. ECOOP’06, pages230–254.

[7] R. Douence, P. Fradet, and M. Sudholt. Composition,Reuse and Interaction Analysis of Stateful Aspects.AOSD’04, pages 141–150.

[8] S. Drossopoulou, A. Petrounias, A. Buckley, andS. Eisenbach. SCHOOL: a Small ChordedObject-Oriented Language. Electr. Notes Theor.Comput. Sci., 135(3):37–47, 2006.

[9] Ericsson Computer Science Laboratory. The ErlangPogramming Language. www.erlang.org.

[10] P. Eugster. Type-based Publish/Subscribe: Conceptsand Experiences. TOPLAS, 29(1), 2007.

[11] P. Eugster, B. Garbinato, and A. Holzer.Location-based publish/subscribe. NCA’05.

[12] P. Eugster and K.R. Jayaram. EventJava: AnExtension of Java for Event Correlation. ECOOP’09,pages 570–594.

[13] L. Fiege, M. Mezini, G. Muhl, and A. Buchmann.Engineering Event-Based Systems with Scopes.ECOOP’02, pages 309–333.

[14] C. Fournet and C. Gonthier. The Reflexive ChemicalAbstract Machine and the Join Calculus. POPL’96,pages 372–385.

[15] D. Frey and G.-C. Roman. Context-Aware PublishSubscribe in Mobile Ad hoc Networks.Coordination’07, pages 37–55.

[16] M. Haahr, R. Meier, P. Nixon, V. Cahill, and E. Jul.Filtering and Scalability in the ECO DistributedEvent Model. PDSE’00, pages 83–92.

[17] Philipp Haller and Tom Van Cutsem. ImplementingJoins using Extensible Pattern Matching.COORDINATION’08, pages 135–152.

[18] R. Hirschfeld, P. Costanza, and M. Haupt. AnIntroduction to Context-Oriented Programming withContextS. GTTSE’07, pages 396–407.

[19] R. Hirschfeld, P. Costanza, and O. Nierstrasz.Context-oriented Programming. Journal of ObjectTechnology, 7(3):125–151, 2008.

[20] Sun Microsystems Inc. Java Message Service -Specification, version 1.1. Technical report, SunMicrosystems Inc., 2005.http://java.sun.com/products/jms/docs.html.

[21] S.G. Von Itzstein and D.A. Kearney. The Expressionof Common Concurrency Patterns in Join Java.PDPTA’04, pages 1021–1025.

[22] K.R. Jayaram and P. Eugster. Context-OrientedProgramming with EventJava. COP’09, pages570–594.

[23] G. Kiczales, E. Hilsdale, J. Hugunin, M. Kersten,J. Palm, and W.G. Griswold. An Overview ofAspectJ. ECOOP 2001.

[24] L. Lamport. Time, Clocks, and the Ordering of Eventsin a Distributed System. Commun. ACM,

21(7):558–565, 1978.

[25] F.J. Mattern. Virtual Time and Global States ofDistributed Systems. WPDA’89, pages 215–226.

[26] R. Meier and V. Cahill. Steam: Event-basedmiddleware for wireless ad hoc networks. DEBS 2002,pages 639–644, 2002.

[27] L.D.B. Navarro, M. Sudholt, W. Vanderperren, B. DeFraine, and D. Suvee. Explicitly Distributed AOPusing AWED. AOSD’06, pages 51–62.

[28] N. Nystrom, M. R. Clarkson, and A. C. Myers.Polyglot: An Extensible Compiler Framework forJava. CC’03, pages 138–152.

[29] F. Pizlo, L. Ziarek, E. Blanton, P. Maj, and J. Vitek.High-level programming of embedded hard real-timedevices. EuroSys ’10, pages 69–82.

[30] H. Plociniczak and S. Eisenbach. JErlang: Erlang withJoins. COORDINATION’10, pages 61–75.

[31] H. Rajan and G.T. Leavens. Ptolemy: A Languagewith Quantified, Typed Events. ECOOP’08, pages155–179.

[32] E.N. Rasmussen. Refined Supercell and TornadoForecast Parameters. Weather and Forecasting,18:530–535, 2003.

[33] J. H. Reppy and Y. Xiao. Specialization of CMLMessage-passing Primitives. POPL’07, pages 315–326.

[34] C. V. Russo. Join Patterns for Visual Basic.OOPSLA’08, pages 53–72.

[35] F.B. Schneider. Implementing Fault-Tolerant ServicesUsing the State Machine Approach: a Tutorial. ACMComputing Surveys, 22(4):299–319, December 1990.

[36] R. Soule, M. Hirzel, R. Grimm, B. Gedik, H. Andrade,V. Kumar, and K.-L. Wu. A Universal Calculus forStream Processing Languages. ESOP’10, pages507–528.

[37] J.H. Spring, J. Privat, R. Guerraoui, and J. Vitek.StreamFlex: High-throughput Stream Programmingin Java. OOPSLA’07, pages 211–228.

[38] M. Sulzmann, E.S.L. Lam, and P. Van Weert. Actorswith Multi-headed Message Receive Patterns.COORDINATION 2008, pages 315–330, 2010.

[39] E. Tanter. Contextual Values. DLS’08, pages 1–10.

[40] J. Yoon, M. Liu, and B. Noble. Random WaypointConsidered Harmful. INFOCOM’03.