X-Original-To: pgsql-general-postgresql.org@postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 2CD089FA373; Mon, 3 Jul 2006 12:03:36 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 07483-09; Mon, 3 Jul 2006 12:03:31 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- X-Greylist: from auto-whitelisted by SQLgrey- Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 144309FA232; Mon, 3 Jul 2006 12:03:30 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.6/8.13.6) with ESMTP id k63F3S3F003098; Mon, 3 Jul 2006 11:03:28 -0400 (EDT) To: Joost Kraaijeveld cc: pgsql-jdbc@postgresql.org, pgsql-general@postgresql.org Subject: Re: [JDBC] Is what I want possible and if so how? In-reply-to: <1151923545.6055.40.camel@localhost> References: <1151923545.6055.40.camel@localhost> Comments: In-reply-to Joost Kraaijeveld message dated "Mon, 03 Jul 2006 12:45:45 +0200" Date: Mon, 03 Jul 2006 11:03:28 -0400 Message-ID: <3097.1151939008@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200607/79 X-Sequence-Number: 97703 Joost Kraaijeveld writes: > I have a table with events that must be handled by multiple clients. It > does not matter which client handles an event, but no two clients may > handle the same event and an event may only handled once. A client can > only determine the availability of an event by querying the database. > The access to the table should be queue-like with synchronization. > My idea was that a client should do a "SELECT" on the table and mark the > selected records as "being handled" to avoid double handling. > I have read the manual about "LOCK", "SET TRANSACTION" and "SELECT...FOR > UPDATE", but from what I understand, they cannot prevent a "SELECT" from > another client, based on the "SELECT". > Is there a way to make this possible? Sure, but everybody has to use SELECT FOR UPDATE and/or UPDATE. For instance, do this in READ COMMITTED mode: begin; select jobid from queue where status = 'waiting' order by priority limit 1 for update; [ if no row returned, rollback, sleep a bit, try again ] update queue set status = 'busy' where jobid = 'prev result'; commit; Once TX1 has selected a row for update, it's locked and TX2 will sleep until TX1 commits before selecting it; then it will see the change of status and TX2's select will not return the row. This isn't entirely perfect because LIMIT acts before FOR UPDATE: TX2's select will return nothing, rather than selecting the next available row as you might wish. So you might want to retry the select several times before deciding there's nothing to do. Also, an index on priority would be a good idea to make the select fast. regards, tom lane