Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 17
Текст из файла (страница 17)
This frees them up to be re-used as soonas you have finished with them. The problem with this approach is thatyou might need the resource again almost immediately after you havefinished using it.Consider the situation where a user is using a web browser on theirmobile phone to browse a website. The radio connection to the basestation takes a few seconds to set up (‘allocate’) and then the downloadof the web page is relatively quick.
Once the web page is downloaded,the web browser might immediately tear down (‘de-allocate’) the radioconnection as it is no longer required. However as soon as the enduser clicks on a link in the web page, the radio connection resourcewould need to be allocated again, leading to the end user waiting fora few seconds whilst the connection is re-established. This would havea negative impact on the end user’s experience of the mobile webbrowser.A possible solution to this problem is for the web browser developerto use Immortal (see page 53) and never de-allocate these resources.However, your component would stop being a ‘good citizen’ and preventthese resources from being shared across the system.ExampleSymbian OS contains a system for recognizing file types, such whethera file is a word-processed document or a specific type of audio or videofile. This system is called the recognizers framework and it uses plug-insto supply the code that identifies specific file types.
Since there is a largenumber of different file types there is a corresponding large number ofrecognizer plug-ins.When loaded, recognizers use a significant amount of RAM in additionto taking time to initialize during device start-up so using Immortal (seepage 53) wouldn’t be appropriate.However, the Mayfly strategy would also not be appropriate becauserecognizers tend to be used in quick succession over a short period suchas when a file browser enumerates all the file types in a directory. Hence,using Mayfly would result in file recognition taking longer because therecognizers would be allocated and de-allocated many times.SolutionThis pattern is based on the tactic of the resource client using a Proxy[Gamma et al., 1994] to access the resource and the resource provider,called the lazy de-allocator.
The resource client takes ownership orLAZY DE-ALLOCATION75releases the underlying resource as frequently as is needed11 but itdelegates the management of the actual lifetime of the resource to thelazy de-allocator, which is never de-allocated. This allows the lazyde-allocator to delay the actual de-allocation of the resource.The idea is that when the resource is no longer required by theresource client, indicated by it releasing the resource, then instead of itbeing immediately unloaded it is only unloaded when a specific conditionis met. This is done in the expectation that there is a good chance theresource is going to be needed again soon so we shouldn’t unnecessarilyde-allocate it since we’d just have to allocate it again.This pattern is written from the point of view of immediately allocatinga resource in the expectation that it’ll be needed almost straight away.There are other patterns that can be composed with this one and thatdiscuss allocation strategies so, for simplicity, an Immortal (see page 53)approach is taken to allocation.StructureThe responsibilities of the objects shown in Figure 3.6 are as follows, inaddition to their description in the chapter introduction:• The resource client creates the lazy de-allocator as soon as it iscreated and then uses the PrepareResourceL() and ReleaseResource() functions to indicate when it is using the lazy deallocator as a resource.• The lazy de-allocator provides both the resource provider and resourceinterfaces to the resource client as well as managing the actual lifetimeof the resource by choosing when to de-allocate it.DynamicsFigure 3.7 shows the resource being continually used and never actuallybeing de-allocated by the lazy de-allocator.In Figure 3.8, the resource is used only infrequently and so the lazyde-allocator has decided to de-allocate it so that it can be shared acrossthe system.
The way that the lazy de-allocator works is as follows:• Each time ReleaseResource() is called on the lazy de-allocatorit calls AddDeallocCallback(). This is the point where the lazyde-allocator decides whether or not to create a callback that will fireat some point in the future to de-allocate the resource.11 Usingthe Mayfly approach.76RESOURCE LIFETIMESFigure 3.6 Structure of the Lazy De-allocation pattern• Each time PrepareResourceL() is called on the lazy de-allocatorit calls RemoveDeallocCallback() to prevent the callback fromfiring so that the resource remains allocated.The most important thing that you need to decide when applying this pattern is how to implement the AddDeallocCallback()function as this will be a key factor in determining the trade-offbetween avoiding the execution cost of allocating an object and sharing the resource with the rest of the system. Some common strategiesinclude:• A timer could be used to call DeallocCallback(). This timerwould be started in AddDeallocCallback() and stopped inRemoveDeallocCallback().• If the lazy de-allocator is used as a Proxy for multiple resources of thesame type, then AddDeallocCallback() might simply ensure thatit maintains a constant pool of unowned but allocated resources.
Thisstrategy is very similar to Pooled Allocation [Weir and Noble, 2000].LAZY DE-ALLOCATIONResource ClientLazy De-allocatorResource77Resource ProviderPrepareResourceL()RemoveDeallocCallback()Use()Use()ReleaseResource()AddDeallocCallback()Resource remainsallocated betweenthese two pointsPrepareResourceL()RemoveDeallocCallback()Use()Use()Use()Use()ReleaseResource()AddDeallocCallback()Figure 3.7 Dynamics of the Lazy De-allocation pattern when the resource is in frequent useImplementationSome notes before we get started:• Just to illustrate the code given here a timer has been chosen as thede-allocation strategy.• For simplicity, the lazy de-allocator only handles a single resourcebut it could easily be extended to handle more than one.• For simplicity, error handling is done using Escalate Errors (see page32) although an alternative error-handling strategy could be used.• C classes are used to demonstrate the implementation though it wouldbe possible to use R classes instead with few changes.78RESOURCE LIFETIMESResource ClientLazy De-allocatorInitial :ResourceResource ProviderPrepareResourceL()RemoveDeallocCallback()Use()Use()ReleaseResource()AddDeallocCallback()Fires because theresource client hasn'tre-used the resourcequickly enoughDeallocCallback()Deallocate()destructor()PrepareResourceL()AllocateL()Subsequent:Resourceconstructor()Use()Use()Figure 3.8Dynamics of the Lazy De-allocation pattern when the resource is not in frequent useResourceThe following code simply defines the resource we are using:class CResource : public CBase{public:// Performs some operation and Leaves if an error occursvoid UseL();}LAZY DE-ALLOCATION79Resource ProviderHere is the resource provider:class CResourceProvider : public CBase{public:// Allocates and returns a new CResource object.
If an error occurs,// it Leaves with a standard Symbian error code.static CResource* AllocateL();// Matching De-allocatorstatic void Deallocate(CResource* aResource);};Lazy De-allocatorThis class makes use of the standard Symbian OS CTimer class12 tohandle the de-allocation callback:class CLazyDeallocator: public CTimer{public:CLazyDeallocator* NewL();∼CLazyDeallocator();public: // Resource provider i/f// Ensure a resource is available for use or Leave if that isn’t// possiblevoid PrepareResourceL();// Signal that the client isn’t using the resource any morevoid ReleaseResource();public: // Resource i/fvoid UseL();private:CLazyDeallocator();void ConstructL();// From CActivevoid RunL();TInt RunError(TInt aError);private:CResource* iResource;};The constructor and destructor of this class are straightforward implementations. One point to note is that, to avoid disrupting other more12 Thisis implemented in terms of Active Objects (see page 133).80RESOURCE LIFETIMESimportant tasks, a low priority is given to the timer and hence to whenthe de-allocation callback is run:CLazyDeallocator::CLazyDeallocator(): CTimer(CActive::EPriorityLow){}// Standard two-phase construction – NewL not shown for conciseness.void CLazyDeallocator::ConstructL(){iResource = CResourceProvider::AllocateL();}CLazyDeallocator::∼CLazyDeallocator(){if (iResource){CResourceProvider::Deallocate(iResource);}}The method for retrieving a resource needs to cancel the de-allocationtimer and ensure that a resource is available for later use:CResource* CLazyDeallocator::PrepareResourceL(){Cancel(); // Stops the de-allocation callback// Ensure we have a resource for use laterif (!iResource){iResource = CResourceProvider::AllocateL();}}The following function, ReleaseResource(), simply starts the timerfor the iResource de-allocation callback:const static TInt KDeallocTimeout = 5000000; // 5 secondsvoid CLazyDeallocator::ReleaseResource(){// Check if we’re already active to avoid a stray signal if a client// incorrectly calls this function twice without calling// PrepareResourceL() in betweenif (!IsActive()){After(KDeallocTimeout);}}The value to use for the de-allocation timeout is dependent on thesituation in which you are using this pattern.