Multiple threads = primary key exception

Discussions

General J2EE: Multiple threads = primary key exception

  1. Multiple threads = primary key exception (5 messages)

    I am developing a system that runs timed tasks. When we execute these tasks, we want to record the event in the dbms. However, multiple tasks can be spawned at the same time, and thus I am running into PrimaryKeyExceptions when one of the threads adds and then immediate subsequent adds fail. I am using the stateless session beans to addEventLog observe the code.... try{ ArrayList successList = new ArrayList(); Integer _lastId = eventLogDax.retrieveLastEventLogId(); int nextIdNum = _lastId.intValue() ; for (int n= 0 ; n 0){ newDO.setEventLogId(eventLogDax.getEventLogId()); } successList.add(newDO ); } return successList; } catch (Throwable e) { setRollbackOnly(); throw ExceptionUtility.createSessionException(getLogger(), e, this +".addEventLog() failure: "); } You assistance will be much appreciated.

    Threaded Messages (5)

  2. Or is the subsequent Add failing becasue your current thread is busy ? The key word to remember is "synchronized"..
  3. I am getting SQLExceptions...[ Go to top ]

    No I am getting SQLExceptions... because it is trying to add keys with ids that already exist. Say I have 10 threads and all of them read the lastEventId as 1001 and thus the incremented id is 1002. ( for each of the 10 threads) Is there a way to store the eventId and increment as needed and would that have to be synchronized as well?
  4. the error[ Go to top ]

    com.ibm.websphere.ce.cm.DuplicateKeyException: ORA-00001: unique constraint (EDXMEC.EVENT_LOG_PK) violated. This is the error even with the synchronized keyword
  5. the error[ Go to top ]

    com.ibm.websphere.ce.cm.DuplicateKeyException: ORA-00001: unique constraint (EDXMEC.EVENT_LOG_PK) violated. This is the error even with the synchronized keyword
  6. Re: the error[ Go to top ]

    So the problem is that each thread starts with the last IDF, and then ++'s it - ending up with the same value. I think you either: a) need to synchronize the whole block - so that the code which retrieves the last value, increments it, and then uses it to add the new row can only be executing in one thread at a time or b) create a singleton object who's task is just to hand out nextId's. That way each thread can be assured of getting a unique next ID.