TObjectManager and threadsafety


did I understand it correctly that when creating an TObjectManager (or TDatabaseManager), passing it an IDBConnection instance, that this makes it not thread-safe? In other words, would I need an TObjectManager instance for each thread? So when setting up a pool of DB connections for thread purposes, I might as well setup a pool of TObjectManagers, connected to those DB connections, right?

PS: If so, this might be worth mentioning in the manual.

Yes, TObjectManager is not thread-safe and you should have one TObjectManager per thread. You do not need to use a pool (and shouldn't) since creating the manager is very lightweight and it keeps references to objects in memory, so better create and destroy one in each thread.

And are the objects themselves threadsafe or should each thread fetch its own data? Or can they be shared among threads? You mention that the Object manager keeps references to objects in memory. That would suggest that another objectmanager in another thread shouldn't be touching/using the same objects. That might turn into a memory hog on bigger systems with lots of users and/or big datasets. Why is the ObjectManager keeping references to the created objects?

The objects are not thread safe, and shouldn't be. It's not a memory hog, not more than using TDataset for example. TObjectManager is analog to TDataset. You open, retrieve data, once you're done with it, release it. There is no need to keep objects in TObjectManager (or even a TObjectManager alive) for too long. The objects are kept in memory for memory management (since the TObjectManager creates objects and its associations, so it's easier if it release them automatically) and also for state management (so in an update operation it knows what changed in the object, comparing the state loaded from the database and the state before updating the database). 

Good practice is create manager, do the db operations, and destroy the manager.

Tnx that clarifies it!

Hi Wagner,

Following the thread-safety thing, I am planning to use uniGUI for some web related forms. 

uniGUi depends on thread-safe objects.

I do understand that TObjectManager is to be created for each thread, that is fine, my presenter layer creates the model where I hold the TObjectManager. When the user closes that form the presenter kills the model and the associated TObjectManager.

However there is the IDBConnection.

Is it going to be one per thread, or can it be global?


IDBConnection should not be shared. You should also create one per thread, or at least create a pool so you can reuse them, but only one thread at time can use the IDBConnection.