db-derby-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Knut Anders Hatlen <knut.hat...@oracle.com>
Subject Re: How does Derby service lock contention among multiple threads?
Date Wed, 16 Jan 2013 09:31:34 GMT
Al Eridani <al.eridani@gmail.com> writes:

> We have an application that has started to use Derby and we are
> running into some lock timeouts.
>
> When several threads are trying to acquire the same lock, how does
> Derby decide which thread to service the next time the lock becomes
> available?
>
> Is it using Java locks? Thread priority? Something else?

Hi Al,

Derby grants locks in the order they were requested. So if thread 1
requested the lock on a certain row before thread 2 did, thread 1 will
be granted the lock on that row before thread 2. (Unless they both
requested a shared lock on the row, in which case they may be granted
the lock at the same time.)

> Am I better off increasing the timeout? Re-trying?

When I code multi-threaded applications, I usually put my transactions
in a loop that rolls back and retries the transaction two or three times
if it fails with an SQLTransientException. That subclass of SQLException
indicates that the failing operation may succeed if it's retried, and
Derby uses it for lock timeouts and deadlocks, and for some other
errors.

And one should also make sure that the transactions don't hold on to
locks longer than necessary. For example: The application should commit
its transactions as soon as it can, and it should try to avoid
time-consuming operations while a transaction is active and holding
locks in the same thread.

> Pointers to documentation/code appreciated. Thanks!

Here's one example of a method that performs a transaction in a loop
until it either succeeds, fails with some other exception than
SQLTransientException, or fails with SQLTransientException many times in
a row:

http://src.opensolaris.org/source/xref/opengrok/trunk/src/org/opensolaris/opengrok/history/JDBCHistoryCache.java#get

Hope this helps,

-- 
Knut Anders

Mime
View raw message