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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.