Utilizing advisory locks
PostgreSQL has highly efficient and sophisticated transaction machinery that is capable of handling locks in a really fine-grained and efficient way. A few years ago, people came up with the idea of using this code to synchronize applications with each other. Thus, advisory locks were born.
When using advisory locks, it is important to mention that they won’t go away on COMMIT
as normal locks do. Therefore, it is really important to make sure that unlocking is done properly and in a totally reliable way.
If you decide to use an advisory lock, what you really lock is a number. So, this isn’t about rows or data; it is really just a number. Here’s how it works:
Session 1 |
Session 2 |
|
|
|
|
|
|
It has to wait |
|
|
It still has to wait |
|
It is still waiting |
Lock is taken |
Table 2.12 – Sessions 1 and 2 on an advisory lock
The first transaction will lock 15
. The second transaction has to wait until this number has been unlocked again. The second session will even wait until after the first one has committed. This is highly important, as you cannot rely on the fact that the end of the transaction nicely and miraculously solving things for you.
If you want to unlock all locked numbers, PostgreSQL offers the pg_advisory_unlock_all()
function to do exactly this:
test=# SELECT pg_advisory_unlock_all(); pg_advisory_unlock_all ------------------------ (1 row)
Sometimes, you might want to see whether you can get a lock and error out if this isn’t possible. To achieve this, PostgreSQL offers a couple of functions; to see a list of all such available functions, enter \df *try*advisory*
at the command line.