TweetFollow Us on Twitter

September 96 - THE OPENDOC ROAD: Facilitating Part Editor Unloading

The OpenDoc Road: Facilitating Part Editor Unloading

Vincent Lo

In the traditional application model, the code for an application typically remains loaded until the process quits. In OpenDoc, starting with version 1.0.1, a part editor is loaded when it's needed during a session and unloaded when it's not. As a result, valuable memory space can be reclaimed and reused by other part editors.

Even though part editor unloading is mostly transparent to part editors, there are a few things a part editor should do to ensure the success of this scheme. I'll describe these things after giving you a closer look at how part editor unloading works. Pay careful attention, because the crash you prevent may be your own.


HOW PART EDITOR UNLOADING WORKS

The part editor unloading mechanism is enabled by facilities provided by SOMobjects(TM) for Mac OS (the Apple implementation for the Macintosh of the IBM SOM(TM) technology). The basis of part editor unloading is a reference-counting system that enables OpenDoc to keep track of which part objects are in use. I'll explain reference counting and then give the gory details of how part libraries are unloaded, which differs for static and dynamic classes.

Every persistent object (part, frame, link, and so on) in OpenDoc is given a reference count by the draft that creates it. When the object is first created or acquired, its reference count is initialized to 1. Whenever the object is acquired after that (through either the draft's or the object's Acquire method), its reference count is incremented by 1. Whenever the object is released (by a call to the object's Release method), its reference count is decremented by 1.

When all clients have released their references to an object, the reference count of the object is 0, and at this point the draft can delete the object to regain the memory it occupies. However, deletion may not be immediate when the object's reference count drops to 0. In actuality, object deletion is deferred until the purge mechanism of the draft is triggered. Typically, a purge is initiated by the storage system (for example, during a save operation) or by the document shell (such as when the document shell realizes that memory is running low).

In response to a purge request, the draft deletes all the persistent objects and storage units that aren't in use -- that is, objects whose reference count is 0. When all the part objects belonging to a certain part editor are deleted, SOM calls the Code Fragment Manager (CFM) to unload the part editor library. The CFM calls the CFMTerminate routine of the part editor library, and both the code and data sections of the library are destroyed. Some details of how the library is unloaded depend on the kind of SOM class it contains -- either static or dynamic.

Objects created using new className and SOM kernel services (somNewObject, somNewClassReference, and SOMobject::somGetClass) are static class objects. Most (if not all) objects created by a part editor fall into this category. A static class is unloaded when the code that created the static class object is unloaded. Therefore, when a part editor is unloaded, all static classes in the same library are unloaded as well. Other interdependent libraries may also be unloaded; there will be more on this later.

Objects created using the runtime name or ID class-lookup services of SOM (for example, SOMClassMgr::somFindClass, somNewObjectByName, or somGetDynamicClassReference) are dynamic class objects. OpenDoc parts are dynamic class objects, since they're created by name. Extension objects are also dynamic because ODExtension is implemented as a dynamic class; subclasses of ODExtension inherit its dynamic property as long as they call the parent's InitExtension method. Other OpenDoc classes will be converted to dynamic classes as the need arises; check the notes accompanying future OpenDoc releases for a listing of these.

A dynamic class guarantees that its code and the code for its inherited classes won't be unloaded until the last object of the class is deleted. When the last instance of a part class is deleted, SOM unloads the CFM library containing the part class.

REFERENCE-COUNTING GOTCHAS

Every persistent object must have a correct reference count for the part editor unloading mechanism to work. If a part object has a reference count that's higher than the correct count, the object will remain valid throughout the session even though it's no longer being used. This object will keep its associated part editor library from being unloaded until the process quits. Conversely, if an object has a reference count that errs on the low side, the object may be deleted, causing its library to be unloaded. Referencing an invalid object pointer usually results in a crash.

The best way to avoid reference-count errors is to familiarize yourself with OpenDoc persistent objects and follow the recipes outlined in the OpenDoc Programmer's Guide for the Mac OS. Be sure to pay special attention to the following potential trouble spots.

Avoid self-referencing. If a part object keeps a reference to itself, its reference count will be at least 1 and its part editor library won't be unloaded until the session ends. Since a reference to the part is passed in as an argument in every ODPart method, a part shouldn't need to store a reference to itself.

Break circular references between parts and frames. Each display frame has a reference to its part (after the part has been internalized). Even though a part isn't required to keep a reference to its display frames, most parts do so for convenience. This creates a circular reference between a part and its display frames, so the reference count alone won't indicate when deleting a part is appropriate. The situation becomes more complicated when the part has embedded frames and also keeps references to them. To break these circular references, OpenDoc offers the Close and Remove protocols.

  • The Close protocol is triggered when a containing part decides to get rid of its runtime-embedded frame objects. The containing part calls the embedded frame's Close method. The frame first calls its part's DisplayFrameClosed method, which should release its reference to the display frame and close its embedded frames (if any) before releasing its reference to the part.

  • The Remove protocol works similarly to the Close protocol. However, the protocol is triggered when a containing part decides to remove its embedded frames from both runtime storage and persistent storage. The Remove protocol is propagated through the ODPart::DisplayFrameRemoved and ODFrame::Remove methods.

Unregister frames and parts when idle time is no longer needed. When a part registers its frame with the OpenDoc dispatcher for idle time, the dispatcher retains a reference to the frame. Until the part editor unregisters the frame object from the dispatcher, the object will remain resident in memory with a reference count greater than 0. This will prevent the object from being deleted and its library from being unloaded. The part editor should unregister the frame when the Remove or Close protocol is triggered.

On rare occasions, a part may have a display frame that's not in the frame hierarchy originated from the root frame. For example, a part may have some frames stored for the View in Window command. Don't internalize those frames and register them for idle time until the frames are actually used.

A part may also register itself with the OpenDoc dispatcher for idle time. As in the case of registered frames, the dispatcher retains a reference to the part object. To ensure that the object is deleted and that its library is unloaded at the earliest possible time, the part editor must unregister itself from the dispatcher as soon as idle time is no longer needed. This usually occurs when all the part's display frames have been closed or removed.

Watch extensions for reference-counting problems. OpenDoc's extension mechanism enables separate parts in a document to communicate with each other directly. By creating an associated extension object, a part editor can extend its part interface to satisfy special needs. To enable efficient communication, the extension object maintains a reference to the part object that created it; the part typically keeps a reference to the extension so that it can give out the same extension object again if it's requested.

In general, an extension object is released before its creator, thus preventing any reference-counting problem for the part. But if the reference count of the extension object isn't maintained correctly, or if the client of the extension object refuses to release it, the part object can detach the extension object from itself by calling ODExtension::BaseRemoved. A well-behaved extension object should then report errors to clients when it's being accessed. An even better idea is to avoid using the base removal mechanism and instead to define the scope and lifespan of an extension.


A LIBRARY-UNLOADING GOTCHA

When a part editor is unloaded, SOM unloads the CFM library associated with the part editor. Moreover, if there's another library in the same library closure as the part editor, the CFM will unload it if it doesn't belong to another library closure. (A library closure is a group of shared libraries whose interdependencies cause them to be loaded together by the CFM.) This means that code other than the part editor residing in the same CFM library closure is unloaded as well. If the developer hasn't foreseen this possibility, it can lead to unfortunate consequences.

Let's consider a typical example. A part editor creates a SOM object from a static class that resides in the same library closure as the part editor. The part editor then installs the object in a name space so that others can access it. If this object doesn't hold a reference to the part, the part may be deleted (and its library closure unloaded) when the object reference is still in the name space. The next time this object is used, a crash will likely occur because the code associated with the object has been unloaded with the part editor.

To prevent this from happening, you should ensure that no class whose code resides in the same library closure as the part editor outlives the part itself. If an object must outlive the part that creates it, the object should be created dynamically. OpenDoc provides a utility function, ODNewObject, to create objects by name. The code in Listing 1 illustrates how a dynamic object is created with ODNewObject.



Listing 1. Creating a dynamic object with ODNewObject
#include "ODNewObj.h"

ODObjectNameSpace* objNameSpace = 
    (ODObjectNameSpace*) nameSpMgr->CreateNameSpace
        (ev, kOSAScriptingTool, kODNULL, 1, kODNSDataTypeODObject);
Sample_ScriptRunnerAgent* agent = 
    (Sample_ScriptRunnerAgent*) ODNewObject
        ("Sample::ScriptRunnerAgent");
objNameSpace->Register(ev, kOSAScriptingTool, agent);


As mentioned earlier, parts and extensions are dynamic objects and thus don't require ODNewObject. ODNewObject is used mainly on SOM classes that a part developer has created.

Once a class has been accessed dynamically, the class remains dynamic until the process exits or the use count of the class maintained by SOM goes to 0. Until then, all object references created for the class are considered dynamic by SOM.

COUNTING ON YOU

Part editor unloading in OpenDoc is a great scheme for managing memory efficiently. But its success depends on the cooperation of each and every part editor. If you keep in mind the gotchas detailed in this column, your part editor will avoid the pitfalls and reap the benefits of wise resource use.

VINCENT LO is Apple's technical lead for OpenDoc. In his leisure time, he loves to travel and sample exotic food. Living in Hong Kong for many years convinced him that no food can scare him, but he'll continue to trot the globe to seek out gustatory challenges.

Thanks to Dave Bice, Erik Eidt, and Troy Gaul for reviewing this column.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.