Child pages
  • EOF-Using EOF-Memory Management
Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Overview

Memory Management in Java is a bit of a black art. When combined with EOF, there are certain issues that you need to be aware of. In WebObjects 5.2, there was a major change to the memory management system in EOF that provided support for WeakReferences to EO snapshots rather than only relying on the previous system of reference counting. This provides for vastly superior memory performance under the same conditions with the same app in 5.2 and above, because there are many cases where references will be released by Java's memory system rather than be held onto by your EOEditingContext.

There is a large overlap between the content about Caching and Freshness and that of Memory Management. Both should be read to fully understand how caching and memory management should play a part in your application design.

General Issues

One important issue to consider prior to taking any drastic measures is whether or not your application really just requires more memory than you are giving it. By default, a Java Virtual Machine gives a Java application 64M of memory. This is not that much memory for an enterprise web application. You can adjust this by setting the "mx" flag on your VM at launch time (-Xmx256M would give you VM 256M of heap to work with instead of the default 64M). Other than just hunting aimlessly in your code, profiling your application is the only way to truly determine your application's memory situation.

The following profiling tools have been verified to work with WebObjects:

Raw Rows

The use of Raw Rows can dramatically decrease your memory usage (and increase your application's performance) at the cost of convenience. This uses less memory than normal EO's, allows better support for fetch limits, and you can still promote them to full-blown EO's when need be. Check out the Raw Rows topic for more information.

Qualify your Fetches

If you are not careful when you fetch, you may bring in huge datasets. When you use an EOFetchSpecification, be mindful to specify the most restrictive EOQualifier that still returns the data you need. Otherwise, you will be potentially faulting in much more data than your application will use, and you decrease your overall application performance because of the data that must be transferred from your database.

Relationships from Enumerated Types to other EO's

It is very common to have EO's that represent "Enumerated Types". For instance, you might have a bug tracking system that has a Severity entity (with individual instances of "Crasher", "Minor", etc) that are referenced by all bugs in the system. It is tempting to always create relationship back-references (i.e. Bug=>Severity, Severity=>>Bug). However, be aware that if you create the reference from Severity back to Bug, any time a Bug is added and you properly use the addObjectToBothSidesOfRelationshipWithKey method, EOF will fault in the ENTIRE "bugs" relationship on Severity prior to adding your new bug to the end of the list. The consequences of this can be crippling to your application. As the number of bugs increases, it will take longer and longer to add a new bug. The recommended best practice for this is to only create Bug=>Severity and NOT create the reverse relationship. In the event that you need to perform that fetch, you can manually construct the EOFetchSpecification rather than use the automatic approach.

Note that this is a filed bug against EOF. One approach that EOF could use is to only add the object to Severity's bugs relationship if the bugs relationship has already been faulted into memory. If the array has not yet been faulted, then causing the fault on insert is potentially very expensive. The reasoning for the current behavior is to maintain the ability to access the newly committed Bug via the Severity bugs relationship prior to committing your transaction (i.e. faulting the relationship from the database wouldn't yet return the newly inserted Bug). This is very important to maintaining object graph consistency pre-saveChanges, but does come at a high performance cost.

Dispose()ing your EOEditingContext

Calling dispose() on your EOEditingContext is not strictly required. When the EOEditingContext is no longer referenced, it will be automatically disposed. However, the question is how long it takes the GC to get to your object. If you call dispose() manually, you won't hurt anything, and you immediately decrement the snapshot reference counts. If your EC is falling out of scope or you set it to null, then it's probably a tossup as to who gets to it first – GC finalizing your EC or you manually calling dispose(). It is recommended that you dispose() your EOEditingContext when you are in a long running process in a single method where the EOEditingContext will not go out-of-scope until the end of the method.

Calling System.gc()

Calling System.gc() is usually a bad idea and can cause performance problems in your application. Additionally, System.gc() is not an order, it is a request, so if your application is relying on this command to execute, you should re-evaluate your application's design, because you may run into problems with this.

Anecdotes on editingContext.invalidateAllObjects()

It can be tempting to resolve memory problems by calling editingContext.invalidateObject(..) or editingContext.invalidateAllObjects(). Avoid this. You will only hurt yourself in the long run. Invalidating is very aggressive and WILL cause exceptions to be thrown if someone in another EOEditingContext is modifying an EO that you invalidate in your EOEditingContext (the shared snapshost will be destroyed, resulting in an exception on .saveChanges in the other context). It should only be used under very controlled situations where you understand the implications of the method.

Chuck Hill

As for invalidating objects, this is something to be avoided. I admit that I have been driven to desperation a couple of times and used this, but only with regrets and reservations.

Art Isbell

I just have a bias against using invalidateAllObjects() because, for me, it's caused more problems than it's solved.

Mike Schrag

The couple of times I resorted to this, I regretted it later, because it ended up screwing me. The biggest thing is you toss snapshots that people might be in the middle of editing, and that's going to cause really funky problems. It's a really heavy-handed way to go.

NSUndoManager

One of the most common memory problems people run into with WebObjects is the NSUndoManager. WebObjects has a particularly cool feature in that it supports an undo stack for EO transactions. Each time you saveChanges, you push an undoable set of changes onto the stack. The downside of this behavior is that you end up with strong references to old EO states, which can be deadly in a large EOF operation.

There are several fixes for this. One is to simply disable the NSUndoManager on your editing context by calling:

editingContext.setUndoManager(null);

It has been referenced that setting the undo manager to null may cause issues with deletes under certain circumstances. In testing this with WebObjects 5.3, the situation could not be reproduced, but if you use WebObjects 5.2 or lower, you should be aware that you might run into problems.

The recommended alternative in this case is to disable the registration of undo events by calling:

editingContext.undoManager().disableUndoRegistration();

Note that setting the undo levels to 0 using setLevelsOfUndo() does not work, as 0 means no limit!

Prior_to_5.2,the_NSUndoManager_had_effectively_infinite_undo_levels_by_default.The_javadoc_of_WO5.3_still_mentions_the_following:

EOEditingContext's_undo_support_is_arbitrarily_deep;_you_can_undo_an_object_repeatedly_until_you_restore_it_to_the_state_it_was_in_when_it_was_first_created_or_fetched_into_its_editing_context._Even_after_saving,_you_can_undo_a_change._To_support_this_feature,_the_NSUndoManager_can_keep_a_lot_of_data_in_memory.

However,_as_of_5.2,_if_you_are_using_the_session_defaultEditingContext,_WOSession_sets_the_default_undo_stack_size_to_10_if_there_is_no_default_size_specified_with_the_WODEFAULTUNDOSTACKLIMIT_parameter.

Lastly_you_can_manually_clear_your_NSUndoManager_when_you_are_done_with_an_operation_by_calling:

__editingContext.undoManager().removeAllActions();

If_you_use_an_NSUndoManager,_it_is_recommended_that_you_call_this_after_performing_very_large_saveChanges_that_involved_large_amounts_of_data.

_WebObjects_5.2+

This_is_a_description_of_the_current_behavior_in_5.3_that_one_might_be_able_to_gather_if_one_were_to,say,_decompile_and_review_the_entire_process-not_that_i_would_ever_do_this_or_condone_it,_of_course-but_if_you_DID,_you_would_probably_gather_exactly_this_info,_which_is_pretty_well_documented(and_seems_to_behave_to-spec)_in_the_5.2_release_notes:

As_of_5.2,the_way_it_works_is:_The_snapshots_in_EODatabase_have_a_reference_count.Each_editing_context_that_fetches_an_EO_increments_the_reference_count.The_EC_holds_onto_that_EO_via_a_WeakReference.When_the_WeakReference_is_reclaimed,_the_snapshot_reference_count_can_decrease(note_CAN,not_IMMEDIATELY_WILL-the_editing_context_keeps_reference_queue_which_is_only_processed_periodically).When_the_count_gets_to_zero,_the_database_forgets_the_snapshot.If_you_have_entity_caching_enabled,_then_EODatabase_ignore_reference_count(or_keeps_it_at_"1"as_a_minimum)_and_it_will_not_go_away_in_a_read-only_scenario.If_you_modify_any_entity_of_that_type_and_saveChanges_in_your_EditingContext,_a_cached_entity's_cache_will_be_entirely_flushed.(NB:_Keep_this_in_mind,_because_if_you_are_caching_a_large_amount_of_data_that_is_writable,_it_will_NOT_be_very_smart_about_updating_that_cache-_It's_blown_away_with_every_update_and_then_it_immediately_reloads_the_entire_set_of_objects_for_that_entity_at_the_next_access)

If_you_have_retainsAllRegisteredObjects_enabled_on_your_editing_context,it_will_NOT_use_WeakReferences._Under_this_circumstance,_the_EO_reference_count_is_only_decreased_when_1)_you_dispose_the_editingcontext_or_2)_you_forget_or_invalidate_the_object.

When_you_modify_an_object_in_an_editing_context,the_editingcontext_keeps_a_strong_reference_to_the_objects_until_you_saveChanges(or_revert,_reset,_etc),_at_which_point_the_strong_references_are_cleared_and_the_only_remaining_reference_is_the_weakreference_like_before.

If_you_have_an_undo_manager_enabled,_it_will_keep_a_strong_reference_to_the_affected_EO's_as_long_as_the_undo_is_around.

I_do_wonder_if_EC's_should_be_using_SoftReferences_instead_of_WeakReferences_..._Would_seem_to_be_more_friendly_to_the_users_of_those_EO's.

If_you_are_using_WO_pre_5.2,then_none_of_the_WeakReference_stuff_applies,_and_everything_is_purely_done_with_snapshot_reference_counting--it_should_behave_like_retainsAllRegisteredObjects=_true_in_5.2.

_WebObjects_Pre_5.2

Prior_to_5.2,all_snapshots_were_simply_reference_counted_by_EOEditingContext.If_an_EO_was_faulted_into_your_EOEditingContext,_it_would_not_go_away_until_the_EOEditingContext_itself_was_disposed._As_a_result,_if_you_have_an_application_deployed_on_a_pre-5.2_WebObjects,_you_will_need_to_adopt_a_strategy_of_periodically_disposing_your_EOEditingContext_and_creating_a_new_one.

_Chuck_Hill

In_our_experience,EOF_is_not_too_good_at_bulk_operations_like_this.If_we_have_a_lot_to_do,_and_don't_need_logic_from_the_EO,_we_wander_down_to_the_EOAccess_level,_and_whip_up_some_batch_insert_statements._You_might_even_want_to_consider_straight_JDBC.

OK_that_said,

  • _save_periodically
  • _don't_retain_references_to_objects_you_have_inserted
  • _if_that_does_not_work,_try_creating_a_new_EC_periodically
  • _a_bit_heavy_handed,_but_ec.invalidateAllObjects()_should_dump_out_all_the_snapshots_as_well.

A_couple_of_useful_comments: http://lists.apple.com/archives/webobjects-dev/2004/Sep/msg00225.html http://lists.apple.com/archives/webobjects-dev/2004/Sep/msg00228.html

It_is_always_interesting_to_read_the_EOF_docs,_the_JavaDocs_are_for_API_only_while_the_EOF_docs_contain_much_valuable_information. http://developer.apple.com/documentation/WebObjects/Enterprise_Objects/index.html

"EOEditingContexts_use_weak_references_to_the_EOEnterpriseObjects_registered_with_them...._EOEditingContexts_hold_all_inserted,_deleted,_or_updated_objects_by_strong_references._These_strong_references_are_cleared_by_the_EOEditingContext_methods_saveChanges..."__--_http://developer.apple.com/documentation/WebObjects/Enterprise_Objects/Managing/chapter_7_section_9.html

_Alan_Ward

Re:_creating_a_new_EC_periodically
I'd_jump_straight_to_this_option_(based_on_my_experience).__I_have_done_a_couple_of_similar_tasks_and
found_that_the_best_way_to_ensure_that_your_app_doesn't_balloon_up_is_to_periodically_ditch_the_EC
and_create_a_new_one.__Seems_like_it_shouldn't_be_necessary...._but_it_works.

_Ken_Anderson

My_guess_is_the_memory_increase_is_due_to_snapshots,which,_as_I_understand_it,_will_never_go_away,_and_wouldn't_be_considered_a_bug(to_me_anyway).

For_dealing_with_a_forever-import_problem_I_had,where_I_didn't_want_the_strong_handed'new_EC'_plan,_I_wrote_this_method,_which_keeps_the_snapshots_down:

_public_static_void_forgetObjectsAndKeypaths(EOEditingContext_ec,_NSArray_eos,_NSArray_keypaths){
___Enumeration_eoEnum=_eos.objectEnumerator();
___while(eoEnum.hasMoreElements())_{
_____EOGenericRecord_eo=_(EOGenericRecord)_eoEnum.nextElement();
_____Enumeration_keypathEnum=_keypaths.objectEnumerator();
_____while(keypathEnum.hasMoreElements())_{
_______String_keypath=_(String)_keypathEnum.nextElement();
_______EOFaulting_faulting=_(EOFaulting)_eo.valueForKeyPath(keypath);
_______if(faulting_!= null && !faulting.isFault())_{
_________if(eo.isToManyKey(keypath))_

Unknown macro: {____________NSArray_relEos_=_(NSArray)_eo.valueForKeyPath(keypath);____________EOHelper.forgetObjects(ec,_relEos);__________}

else

Unknown macro: {____________ec.forgetObject((EOCustomObject)_eo.valueForKeyPath(keypath));__________}

________}
______}
______ec.forgetObject(eo);
____}
__}

You_can_use_it_like_this:

__EOHelper.forgetObjectsAndKeypaths(ec,_arrayOfEOsToForget,_new_NSArray(new_String[]

Unknown macro: {"rel1",_"rel2"}

);

Of_course,_all_the_EOs_in_the_array_need_to_be_the_same_entity_for_keypaths_to_work!

Category:WebObjects

  • No labels