Optimistic Lock Exceptions

Another question:
I'm getting some optimistic lock exceptions for object which I believe
should only be modified in a single transaction. How can I see the context
in which each modification took place?
What is the definition of a 'modification', i.e. what operations on an
object take an optimistic lock?
Thanks,
Tom

Tom-
In article <blj328$1i4$[email protected]>, Tom Davies wrote:
>
Another question:
I'm getting some optimistic lock exceptions for object which I believe
should only be modified in a single transaction. How can I see the context
in which each modification took place?Try catching the lock exception and getting the FailedObject to see which
object failed.
You could also track which objects are being saved by
implementing javax.jdo.InstanceCallbacks and doing some logging in
jdoPreStore(). You could also try watching the SQL log to see if any
suspicious updates are taking place.
What is the definition of a 'modification', i.e. what operations on an
object take an optimistic lock?Any field change or the addition/deletion to any related fields.
Thanks,
Tom--
Marc Prud'hommeaux [email protected]
SolarMetric Inc. http://www.solarmetric.com

Similar Messages

  • Em.merge does not throw Optimistic Lock Exception

    Hello,
    we are using Optimistic Lock Exception in a stateful bean managed transaction.
    I am wondering that there is no Optimistic Lock Exception is thrown after em.merge
    The Optimistic Lock Exception is primary thrown on em.flush - is this right?
    A similar problem is described on
    http://www.nabble.com/Optimistic-Lock-Exception-expected-td22742662.html#a22742662
    See serveroutput: The EclipseLink-5006-Exception is thrown after an em.flush
    14:03:11,657 INFO [STDOUT] updateItem
    14:03:11,657 INFO [STDOUT] [EL Finest]: 2009-04-09 14:03:11.657--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--Merge clone with references com.tup.model.Person@131a24c
    14:03:11,657 INFO [STDOUT] merged
    14:03:11,657 INFO [STDOUT] [EL Finest]: 2009-04-09 14:03:11.657--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--Execute query UpdateObjectQuery(com.tup.model.Person@196649c)
    14:03:11,657 INFO [STDOUT] [EL Fine]: 2009-04-09 14:03:11.657--ClientSession(21268424)--Connection(25845065)--Thread(WorkerThread#0[192.168.1.217:4518])--UPDATE mku_person_ver SET first_name = ? WHERE ((ID = ?) AND (((last_name = ?) AND (first_name = ?)) AND (version = ?)))
    bind => [Bernd 982, 5, Kuls, Bernd 98, 2009-04-09 13:12:15.0]
    14:03:11,672 INFO [STDOUT] [EL Warning]: 2009-04-09 14:03:11.672--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--Exception [EclipseLink-5006] (Eclipse Persistence Services - 1.1.0.r3634): org.eclipse.persistence.exceptions.OptimisticLockException
    Exception Description: The object [com.tup.model.Person@196649c] cannot be updated because it has changed or been deleted since it was last read.
    Class> com.tup.model.Person Primary Key> [5]
    14:03:11,688 INFO [STDOUT] [EL Warning]: 2009-04-09 14:03:11.688--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--javax.persistence.OptimisticLockException: Exception [EclipseLink-5006] (Eclipse Persistence Services - 1.1.0.r3634): org.eclipse.persistence.exceptions.OptimisticLockException
    Exception Description: The object [com.tup.model.Person@196649c] cannot be updated because it has changed or been deleted since it was last read.
    Class> com.tup.model.Person Primary Key> [5]
    14:03:11,688 INFO [STDOUT] OptimisticLockException throws MyApplicationException
    14:03:11,688 INFO [STDOUT] MyApplicationException
    14:03:11,735 INFO [STDOUT] [EL Finer]: 2009-04-09 14:03:11.735--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--TX afterCompletion callback, status=ROLLEDBACK
    14:03:11,750 INFO [STDOUT] [EL Finer]: 2009-04-09 14:03:11.75--UnitOfWork(14218007)--Thread(WorkerThread#0[192.168.1.217:4518])--release unit of work
    14:03:11,750 INFO [STDOUT] [EL Finer]: 2009-04-09 14:03:11.75--ClientSession(21268424)--Thread(WorkerThread#0[192.168.1.217:4518])--client released
    14:03:11,750 ERROR [BMTInterceptor] BMT stateful bean 'ModelFacade' did not complete user transaction properly status=STATUS_MARKED_ROLLBACK
    And by this Exception the transaction's status is set to status=STATUS_MARKED_ROLLBACK.
    The transaction can no longer be used.
    I want to use this transaction further and wrap the OptimisticLockException into an MyApplicationException
    (see serveroutput).
    But no change!
    Any Ideas ?
    Regards,
    Martin Kubitza
    T&P Bochum/Germany

    Hi,
    are you using JPA or TopLink ? Check if there is another exception thrown that produces the error. You can try and catch (Exception ex), which will catch them all. if this works the obviously you don't catch the right exception
    I found a post saying that: "If you trying commit directly after persist w/o doing an explicit
    flush then OptimisticLocking Exception maybe nested inside
    RollBackException. What is the top most error on stack? You can catch
    javax.persistence.PersistenceException and try to do this kind of
    error translation
    public static void getThrowable(javax.persistence.PersistenceException
    perex, int code) {
    boolean updateError = false ;
    boolean deleteError = false ;
    KentException kentex = null ;
    Throwable th = null ;
    if( perex instanceof org.apache.openjpa.persistence.RollbackException) {
    th = perex.getCause();
    if(th instanceof OptimisticLockException) {
    updateError = true ;
    if(perex instanceof OptimisticLockException ){
    updateError = true ;
    th = perex ;
    if(perex instanceof org.apache.openjpa.persistence.EntityNotFoundException) {
    deleteError = true ;
    th = perex ;
    http://n2.nabble.com/OptimisticLockException-confusion.-td210621.html
    Frank

  • Optimistic Lock Exception handler

    Hi,
    In my session bean, i am trying to handle the optimistic error but always get the standard error page.
    My sample code is:
    Public MyObject updateMyObject (MyObject myObject) {
    try {
    em.merge(myObject);
    catch (OptimisticLockException e) {
    return myObject;
    kindly advise how can i handle the exception programmatically en refresh the entity.
    Regards

    Hi,
    are you using JPA or TopLink ? Check if there is another exception thrown that produces the error. You can try and catch (Exception ex), which will catch them all. if this works the obviously you don't catch the right exception
    I found a post saying that: "If you trying commit directly after persist w/o doing an explicit
    flush then OptimisticLocking Exception maybe nested inside
    RollBackException. What is the top most error on stack? You can catch
    javax.persistence.PersistenceException and try to do this kind of
    error translation
    public static void getThrowable(javax.persistence.PersistenceException
    perex, int code) {
    boolean updateError = false ;
    boolean deleteError = false ;
    KentException kentex = null ;
    Throwable th = null ;
    if( perex instanceof org.apache.openjpa.persistence.RollbackException) {
    th = perex.getCause();
    if(th instanceof OptimisticLockException) {
    updateError = true ;
    if(perex instanceof OptimisticLockException ){
    updateError = true ;
    th = perex ;
    if(perex instanceof org.apache.openjpa.persistence.EntityNotFoundException) {
    deleteError = true ;
    th = perex ;
    http://n2.nabble.com/OptimisticLockException-confusion.-td210621.html
    Frank

  • Pessimistic lock exception in a clustered environment

    Hello,
    i am using distributed Cache(DataCache) in a Cluster environment
    (Weblogic 7.0 cluster).
    I got one AdminServer and two ManagedServer running on the same machine.
    The problem occurs when i am using optimistic locking. It seems to be that
    the cache is not beeing synchronized, when i am successivly persisting
    objects and therfore get optimistic lock exceptions.
    When i am using pessimistic locking there is no problem.
    Waht could be the reason for this, maybe the case the all instances
    running on the same machine?
    My properties for the cache are the following:
    com.solarmetric.kodo.DataCacheClass=de.d2vodafone.webe.common.security.
    authorization.jdo.Cache (Cache is a subclass of UDPCache)
    com.solarmetric.kodo.DataCacheProperties=UseMulticast=true
    MulticastGroup=224.0.0.123 (is unique in my environment)
    In the log of my server i got the following messages:
    ignoring update from localhost
    ####<12.02.2003 13:25:11 CET> <Error> <EJB> <pc120514> <ManagedServer2>
    <ExecuteThread: '4' for queue: '__weblogic_admin_rmi_queue'> <kernel
    identity> <> <010026> <Exception during commit of transaction
    4:b57355e6636065c2: javax.jdo.JDOUserException: Errors were detected when
    flushing to the data store. If using optimistic transactions, this could
    indicate that lock violations were detected. The "getNestedExceptions"
    method of this Exception will return the specific errors.
    NestedThrowables:
    javax.jdo.JDOUserException:
    An instance was concurrently modified in another transaction (optimistic
    lock #: 3).
    FailedObject:de.webe.common.security.authorization.DomainImpl-5
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:551)
         at
    com.solarmetric.kodo.ee.EEPersistenceManager.beforeCompletion(EEPersistenceManager.java:192)
         at
    weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInfo.java:540)
         at
    weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCInfo.java:92)
         at
    weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(ServerTransactionImpl.java:1044)
         at
    weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerTransactionImpl.java:1581)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:237)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    NestedThrowablesStackTrace:
    javax.jdo.JDOUserException: An instance was concurrently modified in
    another transaction (optimistic lock #: 3).
    FailedObject:de.d2vodafone.webe.common.security.authorization.DomainImpl-5
         at
    com.solarmetric.kodo.impl.jdbc.ormapping.ClassMapping$1.afterUpdate(ClassMapping.java:611)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatementNonBatch(SQLExecutionManagerImpl.java:563)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatement(SQLExecutionManagerImpl.java:512)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLExecutionManagerImpl.java:406)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionManagerImpl.java:273)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:421)
         at
    com.solarmetric.kodo.runtime.datacache.DataCacheStoreManager.flush(DataCacheStoreManager.java:296)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:549)
         at
    com.solarmetric.kodo.ee.EEPersistenceManager.beforeCompletion(EEPersistenceManager.java:192)
         at
    weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInfo.java:540)
         at
    weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCInfo.java:92)
         at
    weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(ServerTransactionImpl.java:1044)
         at
    weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerTransactionImpl.java:1581)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:237)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.d2vodafone.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.d2vodafone.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    --------------- nested within: ------------------
    weblogic.transaction.RollbackException: Unexpected exception in
    beforeCompletion: sync=com.solarmetric.kodo.ee.EEPersistenceManager@472ddf
    Errors were detected when flushing to the data store. If using optimistic
    transactions, this could indicate that lock violations were detected. The
    "getNestedExceptions" method of this Exception will return the specific
    errors. - with nested exception:
    [javax.jdo.JDOUserException: Errors were detected when flushing to the
    data store.  If using optimistic transactions, this could indicate that
    lock violations were detected.  The "getNestedExceptions" method of this
    Exception will return the specific errors.
    NestedThrowables:
    javax.jdo.JDOUserException: An instance was concurrently modified in
    another transaction (optimistic lock #: 3).
    FailedObject:de.d2vodafone.webe.common.security.authorization.DomainImpl-5]
         at
    weblogic.transaction.internal.TransactionImpl.throwRollbackException(TransactionImpl.java:1561)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:284)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    Thanks for your help
    Best Regards
    Orhan Keskin

    Orhan-
    Is this consistently reproducable, or a rare or one-time occurance? If
    the former, it may be a configuration issue, and we will investigatge
    along that path.
    If it is a rare or one-time occurance, keep in mind that data cache
    synchronization does not guarantee that you will be able to avoid
    optimistic locking exceptions. Whenever using optimistic locking, you
    always need to assume that someday, someone is going to violate that
    lock, unless you place some sort of synchronization atop all the
    database access (e.g., an EJB). It makes any application much more error
    prone (especially since an OL exception is a RuntimeException, and
    frequently people forget that it always needs to be checked for).
    Anyway, if you provide us with some more details, we will be able to
    investigate further.
    In article <[email protected]>, Orhan Keskin wrote:
    Hello,
    i am using distributed Cache(DataCache) in a Cluster environment
    (Weblogic 7.0 cluster).
    I got one AdminServer and two ManagedServer running on the same machine.
    The problem occurs when i am using optimistic locking. It seems to be that
    the cache is not beeing synchronized, when i am successivly persisting
    objects and therfore get optimistic lock exceptions.
    When i am using pessimistic locking there is no problem.
    Waht could be the reason for this, maybe the case the all instances
    running on the same machine?
    My properties for the cache are the following:
    com.solarmetric.kodo.DataCacheClass=de.d2vodafone.webe.common.security.
    authorization.jdo.Cache (Cache is a subclass of UDPCache)
    com.solarmetric.kodo.DataCacheProperties=UseMulticast=true
    MulticastGroup=224.0.0.123 (is unique in my environment)
    In the log of my server i got the following messages:
    ignoring update from localhost
    ####<12.02.2003 13:25:11 CET> <Error> <EJB> <pc120514> <ManagedServer2>
    <ExecuteThread: '4' for queue: '__weblogic_admin_rmi_queue'> <kernel
    identity> <> <010026> <Exception during commit of transaction
    4:b57355e6636065c2: javax.jdo.JDOUserException: Errors were detected when
    flushing to the data store. If using optimistic transactions, this could
    indicate that lock violations were detected. The "getNestedExceptions"
    method of this Exception will return the specific errors.
    NestedThrowables:
    javax.jdo.JDOUserException:
    An instance was concurrently modified in another transaction (optimistic
    lock #: 3).
    FailedObject:de.webe.common.security.authorization.DomainImpl-5
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:551)
         at
    com.solarmetric.kodo.ee.EEPersistenceManager.beforeCompletion(EEPersistenceManager.java:192)
         at
    weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInfo.java:540)
         at
    weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCInfo.java:92)
         at
    weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(ServerTransactionImpl.java:1044)
         at
    weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerTransactionImpl.java:1581)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:237)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    NestedThrowablesStackTrace:
    javax.jdo.JDOUserException: An instance was concurrently modified in
    another transaction (optimistic lock #: 3).
    FailedObject:de.d2vodafone.webe.common.security.authorization.DomainImpl-5
         at
    com.solarmetric.kodo.impl.jdbc.ormapping.ClassMapping$1.afterUpdate(ClassMapping.java:611)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatementNonBatch(SQLExecutionManagerImpl.java:563)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executePreparedStatement(SQLExecutionManagerImpl.java:512)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.executeInternal(SQLExecutionManagerImpl.java:406)
         at
    com.solarmetric.kodo.impl.jdbc.SQLExecutionManagerImpl.flush(SQLExecutionManagerImpl.java:273)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:421)
         at
    com.solarmetric.kodo.runtime.datacache.DataCacheStoreManager.flush(DataCacheStoreManager.java:296)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.flush(PersistenceManagerImpl.java:549)
         at
    com.solarmetric.kodo.ee.EEPersistenceManager.beforeCompletion(EEPersistenceManager.java:192)
         at
    weblogic.transaction.internal.ServerSCInfo.callBeforeCompletions(ServerSCInfo.java:540)
         at
    weblogic.transaction.internal.ServerSCInfo.startPrePrepareAndChain(ServerSCInfo.java:92)
         at
    weblogic.transaction.internal.ServerTransactionImpl.localPrePrepareAndChain(ServerTransactionImpl.java:1044)
         at
    weblogic.transaction.internal.ServerTransactionImpl.globalPrePrepare(ServerTransactionImpl.java:1581)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:237)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.d2vodafone.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.d2vodafone.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    --------------- nested within: ------------------
    weblogic.transaction.RollbackException: Unexpected exception in
    beforeCompletion: sync=com.solarmetric.kodo.ee.EEPersistenceManager@472ddf
    Errors were detected when flushing to the data store. If using optimistic
    transactions, this could indicate that lock violations were detected. The
    "getNestedExceptions" method of this Exception will return the specific
    errors. - with nested exception:
    [javax.jdo.JDOUserException: Errors were detected when flushing to the
    data store.  If using optimistic transactions, this could indicate that
    lock violations were detected.  The "getNestedExceptions" method of this
    Exception will return the specific errors.
    NestedThrowables:
    javax.jdo.JDOUserException: An instance was concurrently modified in
    another transaction (optimistic lock #: 3).
    FailedObject:de.d2vodafone.webe.common.security.authorization.DomainImpl-5]
         at
    weblogic.transaction.internal.TransactionImpl.throwRollbackException(TransactionImpl.java:1561)
         at
    weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:284)
         at
    weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:208)
         at
    weblogic.ejb20.internal.BaseEJBObject.postInvoke(BaseEJBObject.java:278)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl.createUser(AuthorizationServiceBean_8zrrq4_EOImpl.java:170)
         at
    de.webe.common.security.authorization.jdo.AuthorizationServiceBean_8zrrq4_EOImpl_WLSkel.invoke(Unknown
    Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:362)
         at
    weblogic.rmi.cluster.ReplicaAwareServerRef.invoke(ReplicaAwareServerRef.java:114)
         at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:313)
         at
    weblogic.security.service.SecurityServiceManager.runAs(SecurityServiceManager.java:785)
         at
    weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:308)
         at
    weblogic.rmi.internal.BasicExecuteRequest.execute(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:153)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:134)
    Thanks for your help
    Best Regards
    Orhan Keskin
    Marc Prud'hommeaux [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Toplink Optimistic Locking not working with Session Bean facade.

    I am working on Oracle JDeveloper v 10.1.2 and connecting to an Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bit
    The application is based on J2EE architecture and the technology stack uses Struts for presentation/controller framework, Stateless Session EJBs as session facade for custom business services, Simple java classes for the business services, Toplink implementation of DAO layer, Domain objects are mapped to database tables using Toplink Workbench that ships with JDeveloper. The transaction is managed by the session bean and hence the toplink session is configured to use external transaction controller and a named datasource as follows.
    <session xsi:type="server-session">
    <name>DBSession</name>
    <server-platform xsi:type="oc4j-1012-platform"/>
    <event-listener-classes/>
    <logging xsi:type="toplink-log">
    <log-level>fine</log-level>
    <file-name>D:/ToplinkLog.log</file-name>
    </logging>
    <primary-project xsi:type="xml">META-INF/toplink-descriptor.xml</primary-project>
    <login xsi:type="database-login">
    <platform-class>oracle.toplink.platform.database.oracle.Oracle10Platform</platform-class>
    <external-connection-pooling>true</external-connection-pooling>
    <external-transaction-controller>true</external-transaction-controller>
    <sequencing>
    <default-sequence xsi:type="native-sequence">
    <name>Native</name>
    <preallocation-size>1</preallocation-size>
    </default-sequence>
    </sequencing>
    <datasource>jdbc/ORADS</datasource>
    </login>
    </session>
    We intend to use Optimistic Locking based on Timestamp-version locking through an audit field "last_modification_date" of type java.sql.Timestamp. The corresponding database field is also of type Timestamp(6). We are not storing the version in cache.
    The problem we are facing is as follows.. we have an edit screen from where user can edit values for a domain object which are then persisted using Toplink...we expect Toplink to check the database record version (modification_date timestamp) before it applies the update. In DAO implementation, we register the object in a unitOfWork, then set the modified values, however we leave the modification_date (version field) unedited. Now when the application is running, on edit, an exception is thrown by the Session bean before ending the transaction.
    com.evermind.server.rmi.OrionRemoteException: Transaction was rolled back: Error in transaction: java.lang.NullPointerException
         at TrackingMediator_StatelessSessionBeanWrapper2.editOverheadExpenditure(TrackingMediator_StatelessSessionBeanWrapper2.java:1597)
         at com.enbridge.dsm.web.action.TrackingPortfolioAction.editOverheadExpenditure(TrackingPortfolioAction.java:264)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java)
         at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:278)
         at com.enbridge.dsm.web.shared.BaseAction.execute(BaseAction.java:90)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:465)
         at com.enbridge.dsm.web.shared.DSMPojoRequestProcessor.process(DSMPojoRequestProcessor.java:182)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1425)
         at com.sourcebeat.strutslive.common.SLActionServlet.process(SLActionServlet.java:44)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
         at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
         at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
         at com.enbridge.dsm.web.shared.security.SecurityFilter.doFilter(SecurityFilter.java:142)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:645)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:322)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
         at java.lang.Thread.run(Thread.java:534)
         Nested exception is:
    java.lang.NullPointerException
         at oracle.jdbc.driver.PhysicalConnection.commit(PhysicalConnection.java:1190)
         at com.evermind.sql.FilterConnection.commit(FilterConnection.java:209)
         at com.evermind.sql.DriverManagerXAConnection.commit(DriverManagerXAConnection.java:203)
         at com.evermind.server.TransactionEnlistment.commit(TransactionEnlistment.java:251)
         at com.evermind.server.ApplicationServerTransaction.singlePhaseCommit(ApplicationServerTransaction.java:745)
         at com.evermind.server.ApplicationServerTransaction.commit(ApplicationServerTransaction.java:690)
         at com.evermind.server.ApplicationServerTransaction.end(ApplicationServerTransaction.java:1035)
         at TrackingMediator_StatelessSessionBeanWrapper2.editOverheadExpenditure(TrackingMediator_StatelessSessionBeanWrapper2.java:1593)
         at com.enbridge.dsm.web.action.TrackingPortfolioAction.editOverheadExpenditure(TrackingPortfolioAction.java:264)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java)
         at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:278)
         at com.enbridge.dsm.web.shared.BaseAction.execute(BaseAction.java:90)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:465)
         at com.enbridge.dsm.web.shared.DSMPojoRequestProcessor.process(DSMPojoRequestProcessor.java:182)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1425)
         at com.sourcebeat.strutslive.common.SLActionServlet.process(SLActionServlet.java:44)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
         at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
         at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
         at com.enbridge.dsm.web.shared.security.SecurityFilter.doFilter(SecurityFilter.java:142)
         at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:645)
         at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:322)
         at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:790)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:270)
         at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
         at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
         at java.lang.Thread.run(Thread.java:534)
    Note that the exception is thrown at the time when the session bean is about to commit the transaction. i.e. the DAO code did not throw any exception and was able to check the optimistic locking and submit the update transaction.
    I am not able to understand why is the the EJB throwing this weird error with Optimistic locking implementation. The application is working fine when the optimistic locking is disabled.
    I am facing another problem due to this problem... since the session bean throws this exception after exiting the bean implemented method, when trying to commit the transaction, I am not able to mark the session context to setRollbackOnly. Hence if I continue on to another transaction by navigating to another screen in the application, mysteriously the previous transaction gets committed!!... again... weird...

    I am using JDBC driver version 10.1.2.
    I saw this additional error message in JDeveloper console, which for some reason was not logged to my log4j log file... if it helps...
    06/09/22 18:32:10 Thr[thread 6]-TransactionEnlistment.TransactionEnlistment.Caught forgetandRollback XAException e null
    Here are the logs from my Toplink log file....
    [TopLink Info]: 2006.09.22 06:31:46.546--ServerSession(989)--Thread(Thread[HttpRequestHandler-86,5,main])--TopLink, version: Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)
    [TopLink Info]: 2006.09.22 06:31:46.578--ServerSession(989)--Thread(Thread[HttpRequestHandler-86,5,main])--Server: Oracle Application Server Containers for J2EE 10g (10.1.2.0.0)
    [TopLink Config]: 2006.09.22 06:31:46.593--ServerSession(989)--Connection(991)--Thread(Thread[HttpRequestHandler-86,5,main])--connecting(DatabaseLogin(
         platform=>Oracle10Platform
         user name=> ""
         connector=>JNDIConnector datasource name=>jdbc/ORADS
    [TopLink Config]: 2006.09.22 06:31:47.484--ServerSession(989)--Connection(1432)--Thread(Thread[HttpRequestHandler-86,5,main])--Connected: jdbc:oracle:thin:@10.210.16.37:1521:orabld
         User: APP_USR
         Database: Oracle Version: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
         Driver: Oracle JDBC driver Version: 10.1.0.3.0
    [TopLink Config]: 2006.09.22 06:31:47.500--ServerSession(989)--Connection(1433)--Thread(Thread[HttpRequestHandler-86,5,main])--connecting(DatabaseLogin(
         platform=>Oracle10Platform
         user name=> ""
         connector=>JNDIConnector datasource name=>jdbc/ORADS
    [TopLink Config]: 2006.09.22 06:31:47.500--ServerSession(989)--Connection(1434)--Thread(Thread[HttpRequestHandler-86,5,main])--Connected: jdbc:oracle:thin:@10.210.16.37:1521:orabld
         User: APP_USR
         Database: Oracle Version: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
         Driver: Oracle JDBC driver Version: 10.1.0.3.0
    [TopLink Info]: 2006.09.22 06:31:47.671--ServerSession(989)--Thread(Thread[HttpRequestHandler-86,5,main])--DBSession login successful
    [TopLink Fine]: 2006.09.22 06:31:47.703--ServerSession(989)--Connection(1554)--Thread(Thread[HttpRequestHandler-86,5,main])--select * from user_role ur, app_resource ar, role_resource rr where rr.APP_RESOURCE_ID = ar.APP_RESOURCE_ID and rr.USER_ROLE_ID = ur.USER_ROLE_ID
    [TopLink Fine]: 2006.09.22 06:31:49.937--ServerSession(989)--Connection(10245)--Thread(Thread[HttpRequestHandler-86,5,main])--SELECT * FROM PROGRAM_SUB_CAT
    [TopLink Fine]: 2006.09.22 06:31:50.015--ServerSession(989)--Connection(10332)--Thread(Thread[HttpRequestHandler-86,5,main])--SELECT PROGRAM_ID, CREATED_BY_USERID FROM (SELECT CREATED_BY_USERID, ROWNUM PROGRAM_ID FROM (SELECT DISTINCT(CREATED_BY_USERID) CREATED_BY_USERID, 1 AS PROGRAM_ID FROM PROGRAM))
    (I only see my application specific queries after this... no exceptions or debug logs)... as I said before.. the application gives exception in the session bean at the time of commit, and there's no exception raised from Toplink code in DAO...

  • Optimistic Locking fails when version field is part of a Aggregate

    I'm trying to persist a Mapped Object using 9.0.3 Toplink.
    The object uses optimistic locking while the Timestamp versioning field is part of an Aggreate Descriptor. This works well in the Workbench (does not complain).
    Unfortunally it does not work whenever I use the UnitOfWork to register and commit the chances.
    Sample code:
    Object original;
    UnitOfWork unitOfWork = ...          
    Object clone =   unitOfWork.registerExistingObject(original);
    clone.setBarcode("bliblalbu");
    unitOfWork.commit();This throws an nasty OptimisticLockException, complaining about a missing versioning field:
    LOCAL EXCEPTION STACK:
    EXCEPTION [TOPLINK-5004] (TopLink - 9.0.3 (Build 423)): oracle.toplink.exceptions.OptimisticLockException
    EXCEPTION DESCRIPTION: An attempt was made to update the object [BusinessObject:{id:12382902,shorttext:null,barcode:bliblablu,ownerLocation:null,IdEntryName:0,idCs:20579121}], but it has no version number in the identity map.
    It may not have been read before the update was attempted.
    CLASS> de.grob.wps.domain.model.BusinessObjectBO PK> [12382902]
         at oracle.toplink.exceptions.OptimisticLockException.noVersionNumberWhenUpdating(Unknown Source)
         at oracle.toplink.descriptors.VersionLockingPolicy.addLockValuesToTranslationRow(Unknown Source)
         at oracle.toplink.internal.queryframework.DatabaseQueryMechanism.updateObjectForWrite(Unknown Source)
         at oracle.toplink.queryframework.WriteObjectQuery.executeCommit(Unknown Source)
         at oracle.toplink.internal.queryframework.DatabaseQueryMechanism.executeWrite(Unknown Source)
         at oracle.toplink.queryframework.WriteObjectQuery.execute(Unknown Source)
         at oracle.toplink.queryframework.DatabaseQuery.execute(Unknown Source)
         at oracle.toplink.publicinterface.Session.internalExecuteQuery(Unknown Source)
         at oracle.toplink.publicinterface.UnitOfWork.internalExecuteQuery(Unknown Source)
         at oracle.toplink.publicinterface.Session.executeQuery(Unknown Source)
         at oracle.toplink.publicinterface.Session.executeQuery(Unknown Source)
         at oracle.toplink.internal.sessions.CommitManager.commitAllObjects(Unknown Source)
         at oracle.toplink.publicinterface.Session.writeAllObjects(Unknown Source)
         at oracle.toplink.publicinterface.UnitOfWork.commitToDatabase(Unknown Source)
         at oracle.toplink.publicinterface.UnitOfWork.commitRootUnitOfWork(Unknown Source)
         at oracle.toplink.publicinterface.UnitOfWork.commitAndResume(Unknown Source)
         at de.grob.wps.dwarf.domainstore.toplink.ToplinkTransaction.commit(ToplinkTransaction.java:60)
         at de.grob.wps.dwarf.domainstore.toplink.ToplinkPersistenceManager.commit(ToplinkPersistenceManager.java:396)
         at de.grob.wps.dwarf.domainstore.toplink.ToplinkPersistenceManagerTest.testPersistSerializableWithBusinessObjects(ToplinkPersistenceManagerTest.java:87)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at junit.framework.TestCase.runTest(TestCase.java:154)
         at junit.framework.TestCase.runBare(TestCase.java:127)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:392)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:276)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:167)So what can I to fix this problem? BTW the Object I try to persists has been read from database and the IDE debugger shows what that the aggregate object contains java.sql.Timestamp instances.

    Sorry guys. My debugger fooled me. The locking field wasn't initialized in the database. This caused the problem which is fixed now.
    Thx anyway.
    Bye
    Toby

  • ChangeFields optimistic locking

    I am trying to use optmistic locking without changing my database schema by using the descriptor.useChangedFieldsLocking() on my EJB descriptor. Two clients try to do the following.
    1) Query the shallow properties of the EJB (no getters called for unary or collection relationships).
    2) Edit some of that simple data
    3) Submit their changes
    The optimistic locking works okay when just the shallow properties are being retrieved. If a client tries to submit when someone else has already done so, an OptimisticLockException is thrown which is the desired result.
    However, if I wish to traverse one of the relationships on the EJB when it is first queried (by calling a getter for a collection for example) the following happens: When the second client attempts to load and edit this EJB the transaction times out with a deadlock exception.
    I want to traverse relationships for display purposes in this case but in the furture will want to edit something in that relationship with ChangedFieldsLocking also set.
    If anyone could tell me why the second client's transaction times out when it asks for the EJB I would be very grateful.
    Regards
    James.

    Thanks for the reply.
    After further investigation I have found that it's nothing to do with the locking (since I can switch it off and still have the problem) but may be a problem with OC4J (or how I am using it). The situation is as follows:
    1) Client A starts a transaction
    2) Client A asks for ejb1
    3) Client A asks for ejb1.collection()
    4) Client A asks for ejb1.collection(i).someMethod()
    5) Client A uses the result of someMethod()
    (transaction is still open)
    6) Client B starts a transaction
    7) Client B asks for ejb1
    8) Client B asks for ejb1.collection()
    9) Client B asks for ejb1.collection(i).someMethod()
    10) Client B uses the result of someMethod()
    The server hangs on step 9 and never enters someMethod() (the first line is debug and I never see it). Eventually it tells me that the transaction has timed out with a deadlock exception.
    The following comes from the output of a ctrl-break at the point of hanging (someMethod() is getTitle() in this example) :
    "HttpRequestHandler-22629000" prio=5 tid=0x434DE690 nid=0xab4 in Object.wait() [4400f000..4400fd8c]
    at java.lang.Object.wait(Native Method)
    - waiting on <08FC9AC8> (a com.evermind.server.ThreadState)
    at com.evermind.server.ejb.AbstractEJBObject.startCall(AbstractEJBObject.java:226)
    - locked <08FC9AC8> (a com.evermind.server.ThreadState)
    at PersonNamesRemote_EntityBeanWrapper79.getTitle(PersonNamesRemote_EntityBeanWrapper79.java:3227)
    at uk.co.corelogic.framework.common.ejb.entity.PeopleEJB.toBean(PeopleEJB.java:1800)
    at PeopleRemote_EntityBeanWrapper60.toBean(PeopleRemote_EntityBeanWrapper60.java:1742)
    at uk.co.corelogic.framework.common.ejb.session.FrameworkManager.retrieve(FrameworkManager.java:142)
    I am using OC4J 9.0.4, Toplink 9.0.3.3. I have Toplink configured to generate BMP Entity beans.
    My entity bean deployment descriptor has <reentrant>False</reentrant> but <reentrant>True</reentrant> makes no difference. It also has <trans-attribute>Required</trans-attribute> for everything which should be okay and trying <trans-attribute>Supports</trans-attribute> just causes null pointers to be thrown all over the place.
    I will post this message on the OC4J forum too but would appreciate a reply if you have any ideas.
    Thanks.
    James.

  • High concurrency optimistic locking

    Hi there,
    We have an EJB method that roughly does the following; we have a number of buckets that may or may not be full. If one or more are not full we want it to find the one with the most space available and add the item there. Our main problem here is that this method can be called upwards of 1000 times per second and we're now looking for an efficient way to solve the concurrency issue of two different calls both thinking bucket X has space left even though one of the two calls will fill it up :
    THREAD 1 : findEmptyBucket() returns BUCKET1 (1 SPOT LEFT)
    THREAD 2 : findEmptyBucket() returns BUCKET1 (1 SPOT LEFT)
    THREAD 1 : addItemToBucket(BUCKET1) <- FULL NOW
    THREAD 2 : addItemToBucket(BUCKET1) <- WRONG
    Since only optimistic locking is available in the spec for some reason I think the "EJB3" approach is basically (pseudoish) :
    while(!succeeded) {  
        try {  
            Bucket b = findEmptyBucket(...); // Will throw OptimisticLockException?  
            addItemToBucket(b, item);  
            succeeded = true;  
        catch(OptimisticLockException e) {}  
    } This seems horribly inefficient for a call that is almost guaranteed to require dozens of retries during peak hours. Is there any way to optimize this in such a way that we don't have to use optimistic locking? We're trying to solve this without using vendor specific solutions but EJB3 seems to lack the necessary functionality. Suggestions definitely welcome, evne if they are "that's the only way to do it" ;)
    Thanks!

    I think the OptimisticLockingException is thrown after-the-fact. So, if the addItemToBucket() method does a commit (flush), it will generate the exception rather than the find method. Otherwise, if there is no explicit commit call, the exception will be thrown when the EJB method that holds the while loop returns.
    If performance is critical, maybe a Stateful SessionBean with a Stateless Facade would work better. Create a Stateless SessionBean with an addItem() method and a reference to a single stateful bean. The implementation of the stateful session bean would be something like the following standalone program. The stateful bean would have an addItem() method too, but would keep track of a pool of resources internally.
    class ItemBucket { Item i; }
    class Item { String data; }
    class NoBucketsAvailableException extends Exception {}
    public class bucket {
        final static int POOL_SIZE = 4;
        ItemBucket[] bucketPool = new ItemBucket[POOL_SIZE];
        Object[] bucketLocks = new Object[POOL_SIZE];
        void initBucketPool() {
         for(int i=0; i<POOL_SIZE; i++)  {
             bucketPool[i] = new ItemBucket();
             bucketLocks[i] = new Object();
        void addItemToEmptyBucket(Item _i) throws NoBucketsAvailableException {
         int i=0;
         for(; i<POOL_SIZE; i++) {
             if( bucketPool.i == null ) { // possible empty bucket
              synchronized(bucketLocks[i]) {
              if( bucketPool[i].i == null ) {  // double checked locking
                   bucketPool[i].i = _i;
         if( i >= POOL_SIZE) { throw new NoBucketsAvailableException(); }
    public static void main(String[] args) {
         bucket app = new bucket();
         app.initBucketPool();
         Item item = new Item();
         item.data = "test";
         try {
         app.addItemToEmptyBucket(item);
         catch(NoBucketsAvailableException exc) {}

  • Optimistic Locking - Specifying an alternative User message

    Scenario...
    User A selects a record
    User B selects the same record
    User A makes a change and commits/applies it
    User B makes a change to the same record and ties to commit
    Result...User B gets the following message...
    Error in mru internal routine: ORA-20001: Error in MRU: row= 1, ORA-20001: ORA-20001: Current version of data in database has changed since user initiated update process. current checksum = "56693D48DF0C4F9D2A06AE5976FA6E8F", item checksum = "FC863259F75396F19D003B6B5E687758"., update "MAPOWN"."MAP_ALERT_LEVELS" set "MEASURE_ID" = :b1, "MEASURE_DESC" = :b2, "WARN_DFT" = :b3, "DANGER_DFT" = :b4, "WARN_TMP" = :b5, "DANGER_TMP" = :b6, "RECOMMENDATION" = :b7
    PROBLEM
    How do I capture this message and present a more user-friendly one??
    regards
    Paul P

    Paul - I don't know of a way around this other than to code your own optimistic locking logic and raise/handle an exception before the automatic row processing process catches it.
    Scott

  • Optimistic Lock with Parent and Child relationships

    Hi,
    I just have a question regarding optimistic locking. We have a scenario
    where a parent object has many child objects. Both the parent and the
    child objects have a jdolockx column in the database/jdo file.
    It appears that whenever you add a new child to the parent the parent's
    optimistic lock counter is also updated.
    eg
    parent.getChildren().add(child);
    child.setParent(parent);
    Why does this occur? There is no change made to the database table for
    the parent, except for the jdolockx column. Is there something that I can
    do to stop the lock count from incrementing when I child is added?
    We have a scenario where we have many threads of execution wishing to add
    children to a single parent. The parent itself isnt modified but this
    operation fails due to the parent lock counter being incremented.
    Any help would be appreciated
    Thanks
    Luke

    There is state image indicator in Kodo 3 which has more locking options
    beyond a simple number:
    http://solarmetric.com/Software/Documentation/3.0.1/docs/ref_guide_mapping_versionind.html#state-image
    In addition, you can plug your own version indicator.
    Our default optimistic locking avoids the problem of users having no
    idea what is -actually- in the collection/set at any given time.
    Inconsistencies can occur at the datastore level (user 1 adds
    object a to collection, user 2 removes a, user 1 adds object b... which
    should actually be in the DB? {a,b} or or {a}? This is one of the
    many ways in which not tracking changes to a collection/set can be
    hazardous).
    On locking exceptions, errors could be handled in some appropriate
    function (i.e. refresh, re-apply changes if applicable/safe,
    and commit).
    Luke wrote:
    Hi,
    I just have a question regarding optimistic locking. We have a scenario
    where a parent object has many child objects. Both the parent and the
    child objects have a jdolockx column in the database/jdo file.
    It appears that whenever you add a new child to the parent the parent's
    optimistic lock counter is also updated.
    eg
    parent.getChildren().add(child);
    child.setParent(parent);
    Why does this occur? There is no change made to the database table for
    the parent, except for the jdolockx column. Is there something that I can
    do to stop the lock count from incrementing when I child is added?
    We have a scenario where we have many threads of execution wishing to add
    children to a single parent. The parent itself isnt modified but this
    operation fails due to the parent lock counter being incremented.
    Any help would be appreciated
    Thanks
    Luke
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • How to use Optimistic Locking in Toplink

    Hi!
    Iam using Toplink for O/R mapping, and for each table
    iam using one TimeStamp field, and i specified that
    field as Locking filed, by using the Loking option, and checked the TimeStampLocking option.
    Now my question is do i need to update the Timestamp filed
    each time if i create a new record and while modify an existing record.
    And also do i need to compare the Timestamp for the record which client as read previousley to the TimeStamp in the database for the record manullay lik
    suppose t1 is the timeStamp, which i got from the client,
    and t2 is the timestamp which i read from the Database.
    Now my question is, is it necessary to compare the timestamp.

    Once optimistic locking has been configured TopLink will manage the updating and comparing of the OptimisticLocking value. There is no requirement for you to manage this value.
    --Gordon                                                                                                                                                                                                                                                                                                                                                                                       

  • Error in Update Process for optimistic locking

    Hello,
    I tried to create a tabular form according to this How-To:
    http://www.oracle.com/technology/products/database/application_express/howtos/tabular_form.html
    which worked fine until I tried to implement the optimistic locking.
    I use the same update process:
    declare
    l_cks wwv_flow_global.vc_arr2;
    j pls_integer := 1;
    begin
    -- Get original MD5 checksum
    select wwv_flow_item.md5(job,mgr,hiredate,sal,comm,deptno) cks
    BULK COLLECT INTO
    l_cks
    from emp;
    -- Compare the original checksum, l_cks,
    -- with submitted checksum, htmldb_application.g_fcs.
    -- If they are different, raise an error.
    for i in 1..l_cks.count
    loop
    if htmldb_application.g_fcs(i) != l_cks(i) then
    rollback;
    raise_application_error(
              -20001,
         'Current version of data in database has changed '||
              'since user initiated update process.');
    return;
    end if;
    end loop;
    but as soon as I try to apply the changes in the update process I get an error message saying: PLS-00503: RETURN statement required for this return from function
    So, if i delete the row with the "return;" statement, I get no error anymore, but when I test the optimistic locking I get an error as soon as I try to update a row in the first place.
    What am I doing wrong?
    Johnny
    P.S. : I am using Apex 1.6

    Hi Ant, of course......here is the customized pl/sql block I use:
    declare
    l_cks wwv_flow_global.vc_arr2;
    j pls_integer := 1;
    begin
    -- Get original MD5 checksum
    select wwv_flow_item.md5(partition,desig) cks
    BULK COLLECT INTO
    l_cks
    from UNITS;
    -- Compare the original checksum, l_cks,
    -- with submitted checksum, htmldb_application.g_fcs.
    -- If they are different, raise an error.
    for i in 1..l_cks.count
    loop
    if htmldb_application.g_fcs(i) != l_cks(i) then
    rollback;
    raise_application_error(-20001,'Current version of data in database has changed ' || 'since user initiated update process.');
    -- return;
    end if;
    end loop;
    -- update UNITS
    for i in 1..htmldb_application.g_f08.count
    loop
    if htmldb_application.g_f08(i) is not null then
    update UNITS
    set report_id = :P2_REPORT_ID,
    partition = htmldb_application.g_f10(i),
    desig = htmldb_application.g_f11(i)
    where unit_id = htmldb_application.g_f08(i);
    else
    if htmldb_application.g_f10(i) is not null then
    insert into UNITS
    (report_id,
    partition,
    desig)
    values
    (:P2_REPORT_ID,
    htmldb_application.g_f10(i),
    htmldb_application.g_f11(i));
    end if;
    end if;
    end loop;
    end;
    Thanks
    Johnny

  • Optimistic locking/ data concurrency and consistency

    Hi,
    When creating a tabular form using wizard, apex creates its own processes for optimistic locking. But when creating a form on a table, it doesn't create the processes. I suppose I need to create them manually.
    Can anybody show me the steps?
    Thanks!

    Scott,
    Thanks once again.
    2 things:
    My understanding is that I can't change the error message, and that if I want to customize the error message, I need to create my own process for checksum. Is this true? If so, what is the easiest way of doing this?
    I realized it returns an error message and the changes the user made gets lost if he went out for lunch and somebody else made an update on that record. What can I do so the user doesn't lose the data?
    Thanks,

  • [CDO] Schema Locked Exception after update to CDO 4.4

    Hi
    after updating to CDO 4.4 i get a Schema locked exception (see below). This happens as soon as i try to commit a new EMF-model to the server (even with a "fresh" server and repository).
    I'm using the Derby embedded DBStore with a Security Manager, audits enabled and ensureReferentialIntegrity enabled.
    H2 does not work either.
    The Exception:
    org.eclipse.emf.cdo.util.CommitException: Rollback in DBStore: org.eclipse.net4j.db.DBException: Schema locked: SCHEMA_NAME
    at org.eclipse.net4j.internal.db.ddl.DBSchema.assertUnlocked(DBSchema.java:278)
    at org.eclipse.net4j.internal.db.ddl.DBTable.assertUnlocked(DBTable.java:340)
    at org.eclipse.net4j.internal.db.ddl.DBTable.addField(DBTable.java:104)
    at org.eclipse.net4j.internal.db.ddl.DBTable.addField(DBTable.java:89)
    at org.eclipse.emf.cdo.server.db.mapping.AbstractTypeMapping.createDBField(AbstractTypeMapping.java:162)
    at org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.AbstractHorizontalClassMapping.initFields(AbstractHorizontalClassMapping.java:197)
    at org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.AbstractHorizontalClassMapping.<init>(AbstractHorizontalClassMapping.java:107)
    at org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalBranchingClassMapping.<init>(HorizontalBranchingClassMapping.java:205)
    at org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalBranchingMappingStrategy.doCreateClassMapping(HorizontalBranchingMappingStrategy.java:62)
    at org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.createClassMapping(AbstractMappingStrategy.java:659)
    at org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapClasses(AbstractMappingStrategy.java:651)
    at org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapPackageInfos(AbstractMappingStrategy.java:627)
    at org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapPackageUnits(AbstractMappingStrategy.java:616)
    at org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.createMapping(AbstractMappingStrategy.java:538)
    at org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalMappingStrategy.createMapping(HorizontalMappingStrategy.java:144)
    at org.eclipse.emf.cdo.server.internal.db.DBStoreAccessor.writePackageUnits(DBStoreAccessor.java:849)
    at org.eclipse.emf.cdo.spi.server.StoreAccessor.doWrite(StoreAccessor.java:81)
    at org.eclipse.emf.cdo.server.internal.db.DBStoreAccessor.doWrite(DBStoreAccessor.java:828)
    at org.eclipse.emf.cdo.spi.server.StoreAccessorBase.write(StoreAccessorBase.java:152)
    at org.eclipse.emf.cdo.internal.server.TransactionCommitContext.write(TransactionCommitContext.java:651)
    at org.eclipse.emf.cdo.spi.server.InternalCommitContext$1.runLoop(InternalCommitContext.java:48)
    at org.eclipse.emf.cdo.spi.server.InternalCommitContext$1.runLoop(InternalCommitContext.java:1)
    at org.eclipse.net4j.util.om.monitor.ProgressDistributor.run(ProgressDistributor.java:96)
    at org.eclipse.emf.cdo.internal.server.Repository.commitUnsynced(Repository.java:1133)
    at org.eclipse.emf.cdo.internal.server.Repository.commit(Repository.java:1126)
    at org.eclipse.emf.cdo.server.internal.net4j.protocol.CommitTransactionIndication.indicatingCommit(CommitTransactionIndication.java:320)
    at org.eclipse.emf.cdo.server.internal.net4j.protocol.CommitTransactionIndication.indicating(CommitTransactionIndication.java:105)
    at org.eclipse.emf.cdo.server.internal.net4j.protocol.CDOServerIndicationWithMonitoring.indicating(CDOServerIndicationWithMonitoring.java:110)
    at org.eclipse.net4j.signal.IndicationWithMonitoring.indicating(IndicationWithMonitoring.java:98)
    at org.eclipse.net4j.signal.IndicationWithResponse.doExtendedInput(IndicationWithResponse.java:100)
    at org.eclipse.net4j.signal.Signal.doInput(Signal.java:330)
    at org.eclipse.net4j.signal.IndicationWithResponse.execute(IndicationWithResponse.java:73)
    at org.eclipse.net4j.signal.IndicationWithMonitoring.execute(IndicationWithMonitoring.java:67)
    at org.eclipse.net4j.signal.Signal.runSync(Signal.java:254)
    at org.eclipse.net4j.signal.Signal.run(Signal.java:149)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

    Hi Samuel,
    This is the typical exception which occurs when you change your
    metamodel and the models stored in CDO repo haven't been migrated.
    Best Regards.
    Le 13/07/2015 17:14, Samuel Leisering a écrit :
    > Hi
    >
    > after updating to CDO 4.4 i get a Schema locked exception (see below).
    > This happens as soon as i try to commit a new EMF-model to the server
    > (even with a "fresh" server and repository).
    > I'm using the Derby embedded DBStore with a Security Manager, audits
    > enabled and ensureReferentialIntegrity enabled.
    >
    > H2 does not work either.
    >
    > The Exception:
    >
    > org.eclipse.emf.cdo.util.CommitException: Rollback in DBStore:
    > org.eclipse.net4j.db.DBException: Schema locked: SCHEMA_NAME
    > at
    > org.eclipse.net4j.internal.db.ddl.DBSchema.assertUnlocked(DBSchema.java:278)
    >
    > at
    > org.eclipse.net4j.internal.db.ddl.DBTable.assertUnlocked(DBTable.java:340)
    > at
    > org.eclipse.net4j.internal.db.ddl.DBTable.addField(DBTable.java:104)
    > at org.eclipse.net4j.internal.db.ddl.DBTable.addField(DBTable.java:89)
    > at
    > org.eclipse.emf.cdo.server.db.mapping.AbstractTypeMapping.createDBField(AbstractTypeMapping.java:162)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.AbstractHorizontalClassMapping.initFields(AbstractHorizontalClassMapping.java:197)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.AbstractHorizontalClassMapping.<init>(AbstractHorizontalClassMapping.java:107)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalBranchingClassMapping.<init>(HorizontalBranchingClassMapping.java:205)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalBranchingMappingStrategy.doCreateClassMapping(HorizontalBranchingMappingStrategy.java:62)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.createClassMapping(AbstractMappingStrategy.java:659)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapClasses(AbstractMappingStrategy.java:651)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapPackageInfos(AbstractMappingStrategy.java:627)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.mapPackageUnits(AbstractMappingStrategy.java:616)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.AbstractMappingStrategy.createMapping(AbstractMappingStrategy.java:538)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.mapping.horizontal.HorizontalMappingStrategy.createMapping(HorizontalMappingStrategy.java:144)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.db.DBStoreAccessor.writePackageUnits(DBStoreAccessor.java:849)
    >
    > at
    > org.eclipse.emf.cdo.spi.server.StoreAccessor.doWrite(StoreAccessor.java:81)
    > at
    > org.eclipse.emf.cdo.server.internal.db.DBStoreAccessor.doWrite(DBStoreAccessor.java:828)
    >
    > at
    > org.eclipse.emf.cdo.spi.server.StoreAccessorBase.write(StoreAccessorBase.java:152)
    >
    > at
    > org.eclipse.emf.cdo.internal.server.TransactionCommitContext.write(TransactionCommitContext.java:651)
    >
    > at
    > org.eclipse.emf.cdo.spi.server.InternalCommitContext$1.runLoop(InternalCommitContext.java:48)
    >
    > at
    > org.eclipse.emf.cdo.spi.server.InternalCommitContext$1.runLoop(InternalCommitContext.java:1)
    >
    > at
    > org.eclipse.net4j.util.om.monitor.ProgressDistributor.run(ProgressDistributor.java:96)
    >
    > at
    > org.eclipse.emf.cdo.internal.server.Repository.commitUnsynced(Repository.java:1133)
    >
    > at
    > org.eclipse.emf.cdo.internal.server.Repository.commit(Repository.java:1126)
    > at
    > org.eclipse.emf.cdo.server.internal.net4j.protocol.CommitTransactionIndication.indicatingCommit(CommitTransactionIndication.java:320)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.net4j.protocol.CommitTransactionIndication.indicating(CommitTransactionIndication.java:105)
    >
    > at
    > org.eclipse.emf.cdo.server.internal.net4j.protocol.CDOServerIndicationWithMonitoring.indicating(CDOServerIndicationWithMonitoring.java:110)
    >
    > at
    > org.eclipse.net4j.signal.IndicationWithMonitoring.indicating(IndicationWithMonitoring.java:98)
    >
    > at
    > org.eclipse.net4j.signal.IndicationWithResponse.doExtendedInput(IndicationWithResponse.java:100)
    >
    > at org.eclipse.net4j.signal.Signal.doInput(Signal.java:330)
    > at
    > org.eclipse.net4j.signal.IndicationWithResponse.execute(IndicationWithResponse.java:73)
    >
    > at
    > org.eclipse.net4j.signal.IndicationWithMonitoring.execute(IndicationWithMonitoring.java:67)
    >
    > at org.eclipse.net4j.signal.Signal.runSync(Signal.java:254)
    > at org.eclipse.net4j.signal.Signal.run(Signal.java:149)
    > at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    > at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    > at java.lang.Thread.run(Unknown Source)
    >
    Esteban Dugueperoux - Obeo
    Need professional services for Sirius?
    http://www.obeodesigner.com/sirius

  • Aggregate-collection-mapping combined with optimistic-locking

    I've tried to set up an aggregate-collection-mapping and everything seems to be okay. But one thing still lacks: use this aggregate-collection in combination with optimistic-locking. Defining to use optimistic-locking (exactly: timestamp locking) doesn't work. The generated sql-statement doesn't have the wanted timestamp field. Any idea is recommend.

    Hi,
    Aggregate collection mappings do support optimistic locking. You MUST map and store the version value in the object, not the cache. Aggregate objects are not cache independently of their parents so cannot store their version value in the cache.
    Make sure that you have:
    - provided a direc-to-field (non-readonly) mapping for the version field
    - define the locking policy to store the version value in the object, not the cache
    Example:
         descriptor.descriptorIsAggregateCollection();
         descriptor.useTimestampLocking("VERSION", false);
         // SECTION: DIRECTTOFIELDMAPPING
         DirectToFieldMapping directtofieldmapping3 = new DirectToFieldMapping();
         directtofieldmapping3.setAttributeName("version");
         directtofieldmapping3.setIsReadOnly(false );
         directtofieldmapping3.setFieldName("VERSION");
         descriptor.addMapping(directtofieldmapping3);

Maybe you are looking for