users@glassfish.java.net

Re: JPA - entityManager.flush()

From: <glassfish_at_javadesktop.org>
Date: Thu, 17 May 2007 09:16:26 PDT

Well, I'll try to give a simple scenario,

Assuming I have an entity which represents a 'Task'. while a task has a long processing logic, and should be processed -ONLY ONCE-,

So lets assume the task entity look like this:
@Entity
class taks {
//Columns / etc...
  boolean inProcess;
  boolean processed;
}


Now assuming I have an EJB with a timer, being executed each 5 seconds, that scan tasks to process which look like this:

@Stateless
class Scanner implements ScannerInterface {
  @PersistenceContext
  public EntityManager em;

  //Being executed each 5 seconds
  @Timeout
  public scanner() {
    1)Query the DB for tasks that were not processed yet AND are not flagged as 'InProcess'
    2)Somehow flag these entities as they are in process so they can be locked
    3) Process the tasks --> Might take very long time, sometimes more than the interval between each timeout.
  }


So, if part '2' won't update the tasks to the DB and will wait for the end of the transaction until part 3 will end, the next scan would probably load the same tasks that were processed, so tasks might be processed twice.


That is why it is so important to flush the flag that locks the tasks at the begining of the scan before they are being processed, so the next scan would NOT fetch locked tasks.


There might be better algorithm of locking the tasks from being processed again, but that what came up in my mind.


As always - many thanks,

Asaf.
[Message sent by forum member 'trouby' (trouby)]

http://forums.java.net/jive/thread.jspa?messageID=217674