Hibernate and multithreading

We use thread as CurrentSessionContext (current_session_context_class=thread)

Due to performance issues, we load objects in our main thread and process them parallel in different threads.
While saving changes (with the persist-method) in the main thread throw user interaction , we get the ‘detached entity passed to persist’ error.

How can we share session objects between multiple threads?

How can we share session objects between multiple threads?

You should not share Session entities between multiple threads because entities are not meant to be thread-safe, nor their associated Proxies.

If you process data using multiple concurrent batch processors, the main thread should extract the data to be processed, add it to a queue, and the worker threads should take the items from the queue so that only one worker thread process a given batch of data at a time.

OK. we can proceed with one thread at the same time.

must we load an object incl. all dependent children (lazy collections) in the main thread before dispatching it to the worker thread?

If yes, that will take too much time, when we treat very large collections. We want to load objects (from lazy collections) from database as needed while processing them.

How can we reattach objects proceeded in the worker thread, while saving them in the main thread?

OK. we can proceed with one thread at the same time.

That’s not what I said.

must we load an object incl. all dependent children (lazy collections) in the main thread before dispatching it to the worker thread?

Yes, you can do that. Or, let the worker thread execute on just a batch of data at a time using pagination, not associations.

that will take too much time, when we treat very large collections

Switch to queries instead.

We want to load objects (from lazy collections) from database as needed while processing them.

You can do batch processing on subsets of data too.