views:

61

answers:

2

I have already read the hibernate docs about concurrency and I think, I have understood the available locking methods, but I am not sure how I should implement the following scenario.

Two clients F (fast) and S (slow) access the database and can modify the same objects.

Now, one additional requirement: It is critical to the application that client F performs as fast as possible.

How would you solve the problem?

My problem with optimistic locking: Assume that F tries to update its changes but couldn't do this successfully, because S already updated its data. An exception (StaleObjectStateException) will be thrown from hibernate. I will catch this exception and merge the changes and try exactly the same transaction again, right? Then I don't like the case where F retries its transactions until it was successfull and so F could theoretically block a long time. Should I ignore this and hope that this condition is rare in practise? Or can I give my clients something like a database-locking-priority?

Other users can live with this problems:

StaleObjectStateException (Optimistic Locking) ... we get 3 exceptions per 10000 calls.

A: 

First thing that jumps out is that if you have a requirement for A+B to perform as fast as possible, you are going to get massive slow down when catching and handling exceptions. That process is very slow.

I would have to read your post many, many more times to fully grasp what you're saying and offer a better solution but for starters, I would immediately consider not working with exceptions in this case.

gmale
I don't think that catching is that slow, but I would like to avoid the exception, of course. How should I avoid the OptimisticLockException which will be raised if two clients access a database and modify the same object?
Karussell
@Karussell: I understand your question much better now, after your edit. I now see your problem domain is outside my area of expertise--our applications don't service 10s or 100s of thousands of connections/users. That being said, my first gut response was, "make it so two clients can't access a database and modify the same object." Of course, that would probably involve pessimistic locking. So, it seems, if you're going to use optimistic locking in a high-traffic environment, you almost *have to* tolerate a tiny fraction of failures.
gmale
A: 

Catch the StaleObjectException:s and increase the priority of the thread which should be faster. StaleObjectException:s should be rare. Look into pessimistic locking if this is not working for you.

Karussell