views:

52

answers:

2

I would like to have a table in my Oracle database whose rows act as locks. The table would have one column, a varchar, and my clients (Java processes over JDBC) would run statements to acquire and release locks.

The acquire statement should check existence of a row with a given value and insert if not there. The statement should somehow signal to the caller whether the row was free or not.

The release statement should release the lock by deleting the row.

The release statement is straightforward, but what should my acquire statement look like?

+1  A: 

You could define a primary key unique index on lockname. A client would try to:

INSERT  Locks
        (lockname)
VALUES  'MyLock'

If this generates a primary key violation, the client did not succeed in acquiring the lock.

Andomar
+5  A: 

I recommend you use DBMS_LOCK for this purpose. Under the hood, it pretty much does what you're suggesting.

DBMS_LOCK package

Jeffrey Kemp
Voted up. DBMS_LOCK is a much safer option. Doing it manually using a single row is easy until it gets hard - what happens if the client loses connection before deleting the row?? Is there any potential path where an uncaught exception could bypass the release? What happens if both processes do the test to check for a lock, find no lock exists, and then go on to create a lock (I've seen this happen in real life - a 1 in a million situation will occur every few days if there are tens of thousands of transactions a day).
JulesLt
"What happens if both processes do the test to check for a lock, find no lock exists, and then go on to create a lock". You don't write it that way. Instead you try to create the lock and catch the exception if you can't.
Gary