Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 13
Текст из файла (страница 13)
The use of the leavemechanism also frees up the return values of functions in the APIs sothat they can be used for passing actual data.Variants and Extensions• Escalating Errors over a Process BoundaryA limitation of the basic trap and leave operations is that they justescalate errors within a single thread. However, the Symbian OSESCALATE ERRORS47Client–Server framework extends the basic mechanism so that if aleave occurs on the server side it is trapped within the framework. Theerror code is then used to complete the IPC message which initiatedthe operation that failed. When received on the client side this maybe converted into a leave and continue being escalated up the clientcall stack.
However, this is dependent on the implementation of theclient-side DLL for the server.• Escalating Errors without LeavingWhilst this pattern is normally implemented using the leave and trapmechanisms this isn’t an essential part of the pattern. In situationswhere the higher layer didn’t originate the current call stack, it maynot be possible to use a Leave to escalate the error back to it.
Insteadthe error will need to be passed upwards via an explicit function callwhich informs the higher layer of the error that needs to be handled.Examples of this commonly occur when an asynchronous requestfails for some reason since by the time the response comes backthe original call stack no longer exists; for instance, this occurs inCoordinator (see page 211) and Episodes (see page 289).References• Fail Fast (see page 17) is an alternative pattern to this pattern that isintended to solve the problem of handling faults. In general, the twopatterns directly conflict and should not be used to handle the sameerrors. They are designed for different situations.• Client–Server (see page 182) extends the basic trap and leave operations to escalate errors from the server side into the client thread.• The SDL provides further information on using the cleanup stack onSymbian OS at Symbian Developer Library Symbian OS guide Base Using User Library (E32) Memory Management UsingCleanup Support.• [Longshaw and Woods, 2004] discusses similar problems in a differentcontext.3Resource LifetimesThis chapter contains a collection of patterns about when and how toallocate resources, but before we go any further we need to understandwhat we mean by a resource.
For our purposes, a resource is definedas any physical or virtual entity of limited availability that needs to beshared across the system. This can be broken down into two furthertypes:• Ephemeral resources, such as CPU cycles or battery power, have onekey trait: you can’t hold on to them or reserve them for your ownpurposes. They’re there but you can’t keep a grip on them whetheryou use them or not.• Ownable resources, such as RAM, disk space and communicationchannels, are resources that you can hold onto and keep using. Suchresources must normally be reserved for your sole use.
During theperiod that they are allocated to you, these resources cannot be sharedor borrowed by anyone else until you de-allocate them.In this chapter, we’ll be focusing on ownable resources and howto balance the non-functional characteristics of sharing them acrossa system.Whatever their type, the resources available to software on a mobiledevice, are much more constrained than on your average laptop or desktop PC. Compared to mainstream laptops, mobile devices are between10 and 30 times smaller in terms of CPU speed, RAM size and storagespace and are set to remain so in relative terms even as they increasein absolute terms. This is partly to do with the fact that mobile devicesare expected to be carried around in your pocket all the time puttingboth size and weight constraints on the devices. Another factor is that,50RESOURCE LIFETIMESwith over 7 million Symbian OS devices now being sold each month,1device manufacturers are keen to maximize their profits by keeping thecost of the materials in each device as low as possible.
The reason forthis is that to add each additional resource incurs additional hardwarecosts for device manufacturers. For instance, increasing the instructionsprocessed per second means including a faster CPU whilst boosting thememory available to the system means including a bigger RAM chip.When shipping potentially millions of each product, even small savingsper device add up quickly. Also, if an end user finds a device frequentlyrunning out of resources they can’t just plug in a new bit of hardware asthey could on a PC.
The result of this is that, as a developer of softwarebased on Symbian OS, you have to carefully design your code to takeaccount of the scarcity of resources. In general, this means consideringhow to minimize your use of each type of resource and building inthe expectation that at some point a resource you rely on is going torun out.The problem is that you can go too far.
If every resource were to beallocated, used and de-allocated immediately, the resources used acrossthe system would certainly be minimized. However, end users probablywouldn’t care because the device would be so slow as to be unusable.Continually allocating and de-allocating all ownable resources wouldbe non-trivial and would take a significant amount of time and CPUcycles.
If you’ve ever profiled an application, you’ve probably seen thetime spent allocating memory in functions taking a significant proportionof the total time. This is in addition to the introduction of many moreerror paths which would increase the complexity and fragility of yoursoftware. However, reserving a resource for your own use means that thenext request for a similar type of resource elsewhere in the system eitherincreases the total resource usage in the system or fails.A key decision you need to make is when and how much you shouldallocate and de-allocate resources.
You’ll need to consider the followingfactors:• Software throughout a device needs to co-operate in using resourcesand avoid holding onto them unnecessarily.• Software startup needs to be quick, whether it is for the device, anapplication or a service.• The software needs to respond to an event, such as the user pressinga button, with the minimum of delay.• Some resource allocations are potentially unbounded operationsand hence must be avoided in real-time use cases. One example1 www.symbian.com/news/pr/2008/pr20089781.html .RESOURCE LIFETIMES51of this is allocating memory using the default Symbian OS allocator.• Allocating resources may fail and so may introduce additional errorpaths that must be dealt with. For instance, a resource might need toalways be available so that a particular action cannot fail.• Improving a base allocation mechanism2 is going to be hard.
This isbecause they’ve usually been optimized already. For instance, [Bergeret al., 2002] showed that six out of eight applications using custommemory allocators performed better when using a state-of-the-art,general-purpose allocator. Also, if you don’t have access to the sourcecode for the base allocation mechanism then you don’t even havethe opportunity to improve on it without starting again from scratch.When allocating resources other than memory, there could also beunavoidable delays such as network latency.These forces are often contradictory and have to be traded off against oneanother based on the following kinds of factors:• where in the execution path the resource needs to be used• how frequently the resource will be used• who uses the resource• the consequences to the end user’s experience due to the knock-onimpact of failing to allocate a resource.A way of balancing these forces is to use the above factors to decidewhat the lifetime of your use of a resource should be.
You need to choosesomewhere between the two extremes:• Mayfly 3 – you allocate an object, use it and de-allocate it. This is thedefault lifetime and gives the absolute minimum use of the resourceat a potentially high cost in terms of execution time and additionalerror paths.• Immortal – you allocate a resource as soon as possible and neverde-allocate it. This is the opposite of Mayfly and gives the bestperformance and reliability at the expense of the highest resourceusage.The first pattern in this series, Immortal (see page 53), explains theeffects of choosing one of these extremes. The subsequent patterns, Lazy2 By this I mean going from the state of the resource having no users at all to it beingused.3 An insect well known for its very short lifetime (en.wikipedia.org/wiki/Mayfly ).
Alsoknown as Variable Allocation in [Weir and Noble, 2000].52RESOURCE LIFETIMESAllocation (see page 63) and Lazy De-allocation (see page 73), discusshow a compromise between the two can be found.Each of these patterns is described in terms of the following mainobjects:• A resource represents an ownable resource of a specific type.• A resource provider provides an interface through which a resourceobject can be allocated or de-allocated. When a resource has beenallocated, it will not be provided to any other client until it has beende-allocated by the original client.• A resource client uses the resource provider interface to reserve oneor more resource objects by allocating them for its own use. Theresource client then has the responsibility for deciding how long itwishes to hold on to the resource objects before handing them backthe resource provider by de-allocating them.These patterns focus on what resource clients can do to affect thelifetime of a resource.
This is because a common problem is that resourceclients will override strategies employed by resource providers to reduceresource usage by holding onto a resource unnecessarily. However, foreach of the patterns discussed in this chapter you could create a variant inwhich the resource provider takes more of the responsibility for managingresource lifetimes.IMMORTAL53ImmortalIntentAllocate a resource as soon as possible so that, when you come to use itlater, it is guaranteed to be both available and quickly accessible.AKAStatic Allocation, Pre-allocation, Fixed Allocation [Weir and Noble, 2000]ProblemContextA resource is required and the details of how it will be used are wellunderstood.
There is a critical need for its allocation, as well as thepossible failure of the allocation, to be controlled.SummaryYou need to resolve one or more of the following:• You would like to guarantee that allocating the resource will succeed.• The responsiveness of your application or service is negativelyimpacted by the time to allocate one or more resources.• You need to avoid any unbounded resource allocations during areal-time use case.Whichever of the above applies in your situation, it must also bemore important that your application or service always has access to theresource than it is to share the resource with other potential resourceclients.DescriptionOn most mobile devices, some applications or services are consideredessential. What is essential may be mandated by the mobile device creator(e.g.