title: use database as a queue of tasks
body: <p>In one of our java applications (based on postgresql db), we have a database table that maintains a list of tasks to be executed.
  Each row has a json blob for the details of a task as well as scheduled time value.</p>
  
  <p>We have a few java workers/threads whose jobs are to search for tasks that are ready for execution (based on its schedule value), execute and delete them from the table.  Execution of a task may take a few seconds. </p>
  
  <p>The problem is, more than one worker may grab the same row, causing duplicate execution of a task, which is something we want to avoid.</p>
  
  <p>One approach is, when doing <code>select</code> to grab a row, do it with <code>FOR UPDATE</code> to lock the row, supposedly preventing other worker from grabbing the same row that's locked.</p>
  
  <p>My concern with this approach is, the row is only locked when the <code>select</code> transaction is being executed in the db (according to <a href="https://www.postgresql.org/docs/current/static/explicit-locking.html#LOCKING-ROWS" rel="nofollow noreferrer">this</a>), while the java code is actually executing the row/task that's selected,  the locking has gone, another worker can grab it again.</p>
  
  <p>Can some shed some light on whether the above approach is going to work for sure? Thanks!</p>