No matter the programming language is and whatever the database is, the concept should be the same:
I have 2 threads, each locking some database entities and inserting new data in database.
Let’s suppose the fact that those threads run simultanously may cause deadlock exceptions.
Obviously, the main action we can do first of all is to analyse the code deeply to find a good alternative avoiding any deadlocks.
But sometimes, we really can’t avoid them.
Should I catch the exception and retry the concerned process?
At first glance, it would be acceptable, but…what if those conflicting processes are replayed at the same time, other deadlocks again (the snake biting its tail)?
What is a good way to ensure that the processes eventually succeed?
0
Naive solution: Have both threads wait a random amount of time before trying again. Eventually one thread will go before the other (probably sooner rather than later.)
3
Implement some sort of timeout or dead-man mechanism.
For example, here is a (simplified) Enqueue method on a blocking queue:
public void Enqueue(T item)
{
int count = 0;
lock (_locker)
{
while (queue.Count >= MaximumSize)
{
Monitor.Wait(_locker), 100) // Wait for 1/10 of a second.
count++;
if (count >= 100) // Try for 10 seconds
{
throw new DeadlockDetectedException();
}
}
queue.Enqueue(item);
Monitor.PulseAll(_locker);
}
}