Cayenne User Documentation
ObjectContext Memory Management

## Old Memory Management Strategy

Prior to 3.0 release, all implementations of ObjectContext (specifically DataContext) retained hard references to all registered objects on a premise that the context itself would eventually go out of scope and release all those objects. In certain situations such as a context used for processing large data sets and/or a context staying around for a long time (e.g application-scoped context), memory would grow indefinitely, resulting in a leak.

Also there was a little-advertised workaround based on users explicitly calling `ObjectStore.startTrackingNewObjects()` and `ObjectStore.unregisterNewObjects()`.

## New Memory Management Strategy

In release 3.0, by default DataContext uses weak references to store registered objects. So objects are allowed to be garbage collected by the VM if they are not referenced elsewhere in the application. "Elsewhere" usually means one of the following:

- An object is directly or indirectly referenced by the application.
- An object is a part of the cached query result stored by Cayenne.
- An object is "dirty" (i.e. new, modified or deleted). In this case Cayenne ensures that such object is retained at least until commit or rollback.

In addition to saving memory, another positive side effect of this feature is that DataContext retains fewer objects at any given time and hence internal object lookups work somewhat faster on select and commit.

## When to Avoid Weak References

In some cases automatic cleaning of registered objects may result in extra DB trips later on. Depending on a situation, this may or may not be critical, so users will need to weigh the choices of fewer queries vs. smaller memory footprint. In addition to the "dirty objects" scenario described above (and taken care by Cayenne behind the scenes), here are a few more scenarios where a user may choose a different strategy:

- Nested DataContexts: When a child nested DataContext commits to parent, parent using weak references may have already deallocated some of the objects being committed and will have to refetch them.
- ROP: When an ROP client commits to the server, parent server DataContext using weak references may have already deallocated some of the objects being committed and will have to refetch them.

To ensure that weak references are not used, create a DataContext manually, passing a regular `HashMap` to the `ObjectStore` constructor.

TODO: an example, and figure out how to make it a parameter in the Modeler

.
Copyright ©2001-2008 Apache Software Foundation